In Swift, does resetting the property inside didSet trigger another didSet?

前端 未结 3 874
南方客
南方客 2020-12-29 07:17

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         


        
3条回答
  •  心在旅途
    2020-12-29 08:06

    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:

    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.

提交回复
热议问题