Do all @Published variables need to have an initial value in a view model (I am conforming to MVVM) for SwiftUI?
Why can’t I just say that I want the @Published variable of type string with no initial value?
So does that mean that I need to have:
If not how can I get around this?
I was thinking about making an init() for the class, but I would still need to input default values when I initialize the class.
2
Answers
Unlike SwiftUI views, which are Structs, Observable Objects are always classes, and in Swift, all classes must have initializers.
A) Consider making your @Published variable an optional
@Published var title: String?
B) Add an init method
init() { self.title = "" }
Else, there’s way to not have an initial value for a class’ property.
You may find that force unwrapping with "!" will "solve" your problem, but that’s a bad practice, don’t do it; if you don’t have an initial value for your variable, then it must be optional in your case.
But why are you designing a Model, as an observable object, for SwiftUI, consider using simple Structs if you are not intending on persisting (saving to disk), your data, else use Core Data and it’s NSManagedObject class, that is already conforming to ObservableObject.
All stored properties should be initialised somehow. You can delay initialization till construction, like
and later, somewhere in SwiftUI View, create it with value needed in context