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.
This is a known compiler regression SR-12407 . It will be probably fixed in next Xcode version.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.