swift - 在 Swift 中,重置 didSet 中的属性会触发另一个 didSet 吗?

标签 swift swift3 didset property-observer

我正在对此进行测试,如果您更改 didSet 中的值,您将不会再次调用 didSet

var x: Int = 0 {
    didSet {
        if x == 9 { x = 10 }
    }
}

我可以依靠它吗?它记录在某处吗?我在 Swift 编程语言 文档中没有看到它。

最佳答案

我也认为,这是不可能的(也许它不是在 Swift 2 中),但我测试了它并找到了 an example苹果在哪里使用它。 (在“查询和设置类型属性”)

struct AudioChannel {
    static let thresholdLevel = 10
    static var maxInputLevelForAllChannels = 0
    var currentLevel: Int = 0 {
        didSet {
            if currentLevel > AudioChannel.thresholdLevel {
                // cap the new audio level to the threshold level
                currentLevel = AudioChannel.thresholdLevel
            }
            if currentLevel > AudioChannel.maxInputLevelForAllChannels {
                // store this as the new overall maximum input level
                AudioChannel.maxInputLevelForAllChannels = currentLevel
            }
        }
    }
}

在这段代码的下方,有如下注释:

In the first of these two checks, the didSet observer sets currentLevel to a different value. This does not, however, cause the observer to be called again.

关于swift - 在 Swift 中,重置 didSet 中的属性会触发另一个 didSet 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39819081/

相关文章:

ios - 如何在 Swift 中通过操作显示/隐藏 UISearchBar?

ios - UITableViewAutomaticDimension 不适用于包含 tableView 的单元格

swift - 如何设置字符串变量并使其始终小写?

SwiftUI onReceive 是否可以获取oldValue?

ios - 动画 UISlider 的缓冲区轨道变化?

ios - ScrollView 不工作 iOS Swift

ios - 以表单大小显示弹出 View

ios - 删除扩展键盘应用程序后,仍然显示(空)-iOS键盘上的MyKeyboard键盘地球按钮

Swift:本地化字符串数组

Swift didSet 不会触发