先看下面代码
class LightBulb {
static var maxPower:Int = 30 // 最大功率
var currentPower:Int = 0 {
willSet(newCurrentPower){ // 将要赋值(括号里的是新值,也可以不填,直接用newValue)
print("the power is change \(abs(newCurrentPower - currentPower))")
}
didSet(oldCurrentPower) { // 已经赋值(括号里的是旧值,也可以不填,直接用oldValue)
if currentPower == LightBulb.maxPower {
print("Pay attention, the current power go to The highest power")
}
else if currentPower > LightBulb.maxPower {
print("Pay attention, the current power More than the highest power")
currentPower = oldCurrentPower // 附上旧值
}
print("the current power is \(currentPower)")
}
}
}
var lightBulb = LightBulb()
lightBulb.currentPower = 20
lig