简体   繁体   English

.toggle() function on bool 不调用 didSet。 这是一个错误吗?

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

I have a @State Bool variable with didSet on it.我有一个带有 didSet 的 @State Bool 变量。 I want to do something when the variable change therefore I have tried to use didSet.我想在变量更改时做一些事情,因此我尝试使用 didSet。 The problem is when I use the.toggle() function to toggle the state of the bool, didSet is not called.问题是当我使用 the.toggle() function 来切换布尔的 state 时,没有调用 didSet。

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.我只有 2 个按钮: - 一个按钮使用 .toggle() function 切换布尔的 state。 - The next button toggles the state using a basic if/else - 下一个按钮使用基本 if/else 切换 state

The top button using the.toggle() function does not print “set” in the console as expected with the didSet on the variable.使用 the.toggle() function 的顶部按钮不会像预期的那样在控制台中打印“set”,变量上的 didSet。 The bottom button does as expected.底部按钮按预期工作。

This is a known compiler regression SR-12407 .这是一个已知的编译器回归SR-12407 It will be probably fixed in next Xcode version.它可能会在下一个 Xcode 版本中修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM