.toggle() function on bool does not call didSet. Is this a bug?

懵懂的女人 提交于 2021-02-11 05:10:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!