1

I have a View Model defined as such:

class MyViewModel: ObservableObject {
    @Published public var logs: String = ""
}

I would like to modify the logs property from the global scope of my Swift code without initializing MyViewModel like so:

MyViewModel.logs = "log message\n"

I tried making the logs property static:

@Published public static var logs: String = ""

However I get this error:

'wrappedValue' is unavailable: @Published is only available on properties of classes

How do I modify the published property without an instance of MyViewModel?

Jasjeev
  • 385
  • 1
  • 4
  • 17

1 Answers1

4

you could try using a singleton pattern, such as

class MyViewModel: ObservableObject {
    @Published public var logs: String = ""
    
    public static let shared = MyViewModel()  // <--- here
}

then

MyViewModel.shared.logs = "log message\n"