본문 바로가기
Smart Device/Swift

Swift Property Observer

by 언덕너머에 2015. 6. 9.

- 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



'Smart Device > Swift' 카테고리의 다른 글

Swift Initialization Parameter  (0) 2015.06.23
Swift 상속(Inheritance)  (0) 2015.06.22
Swift mutating  (0) 2015.06.09
Swift 함수 #10 Function Type  (0) 2015.06.02
Swift 함수 #9 In-Out 파라미터  (0) 2015.06.02