swift

swift属性观察器

2016-11-30  本文已影响65人  Maggie的小蜗居

OC里面可以重写属性的get和set方法,swift里没有对应的写法,但有属性观察器
属性观察器会监控和响应属性值变化,每次属性设置值时都会调用属性观察器

swift里提供了属性观察器:

willSet会将新的属性值作为参数传入,可以为这个参数指定名称,不指定则为newValue

didSet则是将旧的属性值作为参数传入,不指定参数名称则为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
上一篇 下一篇

猜你喜欢

热点阅读