Swift 属性监视器

class StepCounter {
    var totalSteps: Int = 0 {
        //可省略newTotalSteps,swift默认为newValue,在didSet中的oldValue就是使用了swift的默认值
        willSet(newTotalSteps) {
            println("TotalSteps = \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue {
                println("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}

let stepCounter = StepCounter()
stepCounter.totalSteps = 100
stepCounter.totalSteps = 200
stepCounter.totalSteps = 300

Output

TotalSteps = 100
Added 100 steps
TotalSteps = 200
Added 100 steps
TotalSteps = 300
Added 100 steps