问题
I have a @State Bool variable with didSet on it. I want to do something when the variable change therefore I have tried to use didSet. The problem is when I use the .toggle() function to toggle the state of the bool, didSet is not called.
Take this code for example:
import SwiftUI
struct SwiftUIView: View {
@State var testBool = false {
didSet {
print("set")
}
}
var body: some View {
VStack {
Button(action: {
self.testBool.toggle()
}) {
Text("Toggle with .toggle()")
}
Button(action: {
if self.testBool {
self.testBool = false
} else {
self.testBool = true
}
}) {
Text("Toggle with if")
}
}
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
All I have is 2 buttons: - One button toggles the state of the bool using the .toggle() function. - The next button toggles the state using a basic if/else
The top button using the .toggle() function does not print “set” in the console as expected with the didSet on the variable. The bottom button does as expected.
回答1:
This is a known compiler regression SR-12407. It will be probably fixed in next Xcode version.
来源:https://stackoverflow.com/questions/61247370/toggle-function-on-bool-does-not-call-didset-is-this-a-bug