使用代码:
import Foundation
class StepCount{
var totalSteps : Int = 0 {
willSet(newTotalSteps){
print("新的值为:\(newTotalSteps)")
}
didSet(old){
if(totalSteps > old) {
print("与原来的值相比增减了\(totalSteps - old)个值")
}
}
}
}
let stepCount = StepCount()
stepCount.totalSteps = 0
stepCount.totalSteps = 100
stepCount.totalSteps = 500
stepCount.totalSteps = 800
输出:
新的值为:0
新的值为:100
与原来的值相比增减了100个值
新的值为:500
与原来的值相比增减了400个值
新的值为:800
与原来的值相比增减了300个值
Program ended with exit code: 0