OC里面可以重寫屬性的get和set方法,swift里沒有對應(yīng)的寫法凉唐,但有屬性觀察器
屬性觀察器會監(jiān)控和響應(yīng)屬性值變化,每次屬性設(shè)置值時都會調(diào)用屬性觀察器
swift里提供了屬性觀察器:
- willSet 在新的值即將被設(shè)置時調(diào)用,還沒設(shè)置
- didSet 在新的值被設(shè)置之后調(diào)用
willSet會將新的屬性值作為參數(shù)傳入,可以為這個參數(shù)指定名稱忱屑,不指定則為newValue
didSet則是將舊的屬性值作為參數(shù)傳入,不指定參數(shù)名稱則為oldValue
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print(" \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// 200
// 200 steps
stepCounter.totalSteps = 360
// 360
// 160 steps