A question about init of SwiftUI Views

In the 'I don't understand why this is happening' category, I'm attempting to initialize a state variable in a View struct, however the initialized value doesn't appear to be sticking. Can any of you see why?


I see the following console output:

didSet was called

modelValue: 0 newValue: 12


when I run the code below

also in the ui the displayed value is 0 when I'd expect it to be 12




code:

struct ContentView: View {
    @State var modelValue: Int? {
        didSet {
            print("didSet was called")
        }
    }
    init() {
        updateValue()
    }
    func updateValue() {
        let newValue = 12
        modelValue = newValue
        print("modelValue: \(modelValue ?? 0)    newValue: \(newValue)")

    }
    var body: some View {
        Text("displayValue: \(modelValue ?? 0)")
    }
}
Answered by eleethesontai in 408752022

in the init use the

modelValue = State(initialValue value: newValue)
Accepted Answer

in the init use the

modelValue = State(initialValue value: newValue)
I tested

need to add an underscore infront

Code Block
_modelValue = State(initalValue: newValue)

A question about init of SwiftUI Views
 
 
Q