0
    struct Test {
        
        @State private var steps = UserDefaults.standard.integer(forKey: "steps") {
            didSet {
                steps = UserDefaults.standard.integer(forKey: "steps")
            }
        }
        
        var body: some View {
            Stepper("Go up or down: \(steps)", value: $steps)
                .onChange(of: steps) { newValue in
                    UserDefaults.standard.set(newValue, forKey: "steps")
                }
        }
    }

Using didSet with a binding value doesn't call didSet method. Shouldn't it be called since the value is changing? So, I'm unable to save and show the saved value after this View is pushed back and forth from Navigation view. How should I solve this issue?

Aashish
  • 2,532
  • 2
  • 23
  • 28

1 Answers1

1

For brief explanation: Asperi's answer @ stackoverflow.com/a/62810288/12299030 )

Using @AppStorage instead of UserDefaults, it will automatically reinvoke your view’s body property when the value changes. That is, this wrapper effectively watches a key in UserDefaults, and will refresh your UI if that key changes. Perfect for Binding values.

struct Test {
    
    @AppStorage("steps") var steps = 0
    
    var body: some View {
        Stepper("Go up or down: \(steps)", value: $steps)
    }
}
Aashish
  • 2,532
  • 2
  • 23
  • 28
  • will it always start with a value of 0? or only if the app storage does not contain any value for steps does it use the value of 0? otherwise, if it has a value then it returns it instead – chitgoks Nov 30 '22 at 09:28