Search code examples
swiftswiftuiswiftui-state

SwiftUI State value doesn't change


I am not familiar with State. I tested the code:

import SwiftUI
class TestState {
    @State var a: Int = 3
    func increaseA() {
        print("before \(a)") //3
        a += 1
        print("after \(a)") //3?
    }
}

TestState().increaseA()

It happens that the printed value are both 3! Where did I do wrong?

After the comment that State should be in a View, I tested the code:

import SwiftUI
struct TestState: View {
    @State var a: Int = 3
    func increaseA() {
        print("before \(a)")
        a += 1
        print("after \(a)")
    }

    var body: some View {
        increaseA()
        return Text(a.description)
    }
}

It happens that the Text show "3", not "4". I don't understand.


Solution

  • @State keyword was first intrroduced in Swift5.1, it's a @propertyWrapper, has previously been called @propertyDelegate. For more details check property-wrappers.md. AS PAUL HUDSON SAID : @State is specifically designed for use by the local view, Apple recommends marking @State properties as private to really re-enforce that they aren’t designed to be accessed elsewhere: