本文介绍了在Swift中,重置didSet中的属性会触发另一个didSet吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试,看来如果您在didSet中更改值,则不会再调用didSet.

I'm testing this and it appears that if you change the value within didSet, you do not get another call to didSet.

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

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

Can I rely on this? Is it documented somewhere? I don't see it in the Swift Programming Language document.

推荐答案

我还认为这是不可能的(也许在Swift 2中不是),但是我对其进行了测试并找到了示例苹果在哪里使用它. (在查询和设置类型属性"中)

I also thought, that this is not possible (maybe it wasn't in Swift 2), but I tested it and found an example where Apple uses this. (At "Querying and Setting Type Properties")

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
            }
        }
    }
}

在这段代码下,有以下注释:

And below this piece of code, there is the following note:

这篇关于在Swift中,重置didSet中的属性会触发另一个didSet吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:25