Smart Device/Swift

Swift Property Observer

언덕너머에 2015. 6. 9. 10:17

- Property Observer

속성값의 변화가 발생할 때 원하는 액션을 취할 수 있는 기능을 제공한다.

이 기능을 Property Observer라고 한다.


 * willSet : 속성의 값이 저장되기 직전에 호출된다.

 * didSet : 속성의 값이 변경된 직후에 호출된다.

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            println("[willSet] 호출, 새로운 값: \(newTotalSteps)")
        }
        didSet {
            println("[didSet] 호출")
            if totalSteps > oldValue {
                println("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}

let stepCounter = StepCounter()

stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896