2
votes

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?

enter image description here

So does that mean that I need to have: enter image description here

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
classes don't have a memberwise initializer that structs have, so you need to explicitly provide an init that initializes the properties. It's not unique @Published properties - New Dev
A "type of string with no initial value" is an optional string - String? - If that is what you want then change the type of your property. Of course, you then need to deal with unwrapping the value, so you may find an empty string is a simpler choice - Paulw11

2 Answers

3
votes

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.

0
votes

All stored properties should be initialised somehow. You can delay initialization till construction, like

final class ViewModel: ObservableObject {
   @Published var title: String

   init(title: String) {
     self.title = title
   }
}

and later, somewhere in SwiftUI View, create it with value needed in context

ViewModel(title: "some value")