skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search