在 Swift 中,重置 didSet 中的属性是否会触发另一个 didSet? [英] In Swift, does resetting the property inside didSet trigger another didSet?

查看:20
本文介绍了在 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 Programming Language 文档中没有看到它.

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:

在这两个检查的第一个中,didSet 观察者将 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 中,重置 didSet 中的属性是否会触发另一个 didSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆