swiftuixcode15ios17

Confusion with correct way to call Observable?


I am seeing that there may be two ways to call a Class from other Views or Models. The following is what I have created:

import Foundation
import Observation

@Observable 
class User {
    var EmailAddress = ""
    var Password = ""
}

And have seen it called either:

@State var user: User

or

@State var user = User()

This one is the preferred?


Solution

  • The second one with private access control is the correct way to use @State / @StateObject.

    After Observation

    Since user class no longer had to conform to ObservableObject. @StateObject -> @State is sufficient.

    @State private var user = User()
    

    Before Observation

    According to Apple documentations about @State and @StateObject:

    Even for a configurable state object, you still declare it as private. This ensures that you can’t accidentally set the parameter through a memberwise initializer of the view, because doing so can conflict with the framework’s storage management and produce unexpected results.

    So, it should be @StateObject, since you stored an Object rather than a single property.

    @StateObject private var user = User()
    

    Notice: you're still allowed to use @State in this circumstance. However, the view that listened to the state object will only re-render if the reference to the object changes, instead of updating when these @Published properties change.