I'm using @AppStorage along with a SwiftUI Toggle to manage a UserDefaults variable. My expectation is to perform some operations when the variable changes due to the Toggle interaction, so I need to execute some code in the willSet part of my @AppStorage variable.
However, when I directly bind the @AppStorage variable to the Toggle's isOn state, willSet doesn't trigger. In contrast, when I bind a @State variable to the Toggle and modify the @AppStorage variable when the @State variable changes, the code in willSet does get executed.
Why is this the case? Why does the internal modification of the @AppStorage variable by the Toggle seem to bypass my willSet? Is there a more elegant way to achieve my requirements?
Here's the sample code to illustrate the issue:
struct ContentView: View {
@State var stateVariable = false
@AppStorage("userDefaultVariable") var userDefaultVariable: Bool = false {
willSet {
print("userDefaultVariable will set, newValue: \(newValue)")
}
}
var body: some View {
VStack{
Toggle("Directly modify userDefaultVariable",isOn: $userDefaultVariable)
Toggle("Indirectly modify userDefaultVariable",isOn: $stateVariable)
.onChange(of: stateVariable, perform: { value in
userDefaultVariable = value
})
}
}
}
In this code, the "Directly modify userDefaultVariable" Toggle does not trigger the print statement in the willSet of userDefaultVariable. However, the "Indirectly modify userDefaultVariable" Toggle does trigger the print statement when it modifies the @State variable stateVariable, which in turn modifies userDefaultVariable.