variablesswiftuistateinitialization-order

In SwiftUI, why is a @State variable silently ignored in init()?


Based on the order of the output in the xcode's console, it seems to suggest that default assignment happens before the execution of init(). However, the assignment in init() does not take effect. Here is the code:

TestStateVar(a_stateVar: 5)

...

struct TestStateVar: View {
    @State private var stateVar = -1
    
    init(a_stateVar: Int) {
        print("init-1: self.stateVar = \(self.stateVar)|a_stateVar = \(a_stateVar)")
        self.stateVar = a_stateVar
        print("init-2: self.stateVar = \(self.stateVar)")
    }
    
    var body: some View {
        Text("Test")
            .onAppear() {
                print("onAppear: self.stateVar = \(self.stateVar)")
            }
    }
}

Here is the output from the xcode's console:

init-1: self.stateVar = -1|a_stateVar = 5
init-2: self.stateVar = -1

onAppear: self.stateVar = -1

Is it possible, i.e., using some sort of linting, to configure xcode to detect this bug?


Solution

  • try using this way to initialise a @State var, such as:

    init(a_stateVar: Int) {
         print("init-1: self.stateVar = \(self.stateVar) | a_stateVar = \(a_stateVar)")
         _stateVar = State(initialValue: a_stateVar) // <--- here
         print("init-2: self.stateVar = \(self.stateVar)")
     }