When overriding the didSet observer of a property results in recursion, why?
class TwiceInt {
var value:Int = 0 {
didSet {
value *= 2
Putting a println() in both didSet blocks, you can see that it repeatedly calls the super-implementation first, then the override, then super, then override... until it explodes.
I can only image that this is a bug in Swift. I get the same issue in Swift 1.2 (bundled with the Xcode 6.3 beta).
It should definitely function, at least as I read it. From https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID254:
NOTE
If you assign a value to a property within its own didSet observer, the new value that you assign will replace the one that was just set.
and after their AudioChannel sample (quoted below the note):
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.
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
}
}
}
}