newbieHere
newbieHere

Reputation: 286

Why I can't I assign a value to an @State var in SwiftUI init?

Why does this assignment to an @State var in init not work?

class getOldValuesFromDb : ObservableObject {
    @State var oldValue: Int = 0

    init(){
        let val = 999
        self.oldValue = val
        print("OldValue: \(self.oldValue) and Val: \(val)")
    }
}

The value for the val is displayed correctly, but as I assigned it to the oldValue, it still has a value of zero. My print() looks exactly like this: OldValue: 0 and Val: 999 How it's possible?

Upvotes: 5

Views: 1453

Answers (1)

AnderCover
AnderCover

Reputation: 2661

I'm not sure that @State is supposed to be used outside of a View.

From Apple documentation:

SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.

and

You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing it. It is safe to mutate state properties from any thread.

Did you try using @Published instead ?

Upvotes: 4

Related Questions