Swift 3.0 Property Observers

클래스를 상속받아 기존의 연산 프로퍼티를 재정의하여 나타내줄 수 있다.

//: Playground - noun: a place where people can play

import UIKit

class Account {
    var credit : Int = 0 {
        willSet {
            print("잔액이 \(credit)원에서 \(newValue)원으로 변경될 예정입니다.")
        }
        didSet {
            print("잔액이 \(oldValue)원에서 \(credit)원으로 변경되었습니다.")
        }
    }
    var dollarValue:Double {
        get {
            print(credit)
            return Double(credit)/1000
        }
        set {
            credit = Int(newValue * 1000)
            print("잔액이 \(newValue)달러로 변경 중입니다.")
        }
    }
}

class ForeignAccount : Account {
    override var dollarValue: Double {
        willSet {
            print("잔액이 \(dollarValue)달레에서 \(newValue)달러로 변경될 예정입니다.")
        }
        didSet {
            print("잔액이 \(oldValue)달레에서 \(dollarValue)달러로 변경되었습니다.")
        }
    }
}

let myAccount : ForeignAccount = ForeignAccount()
//잔액이 0원에서 1000원으로 변경되었습니다.

myAccount.credit=1000
//잔액이 0원에서 1000원으로 변경되었습니다.

myAccount.dollarValue = 2
잔액이 1.0달레에서 2.0달러로 변경될 예정입니다.
잔액이 1000원에서 2000원으로 변경될 예정입니다.
잔액이 1000원에서 2000원으로 변경되었습니다.
잔액이 2.0달러로 변경 중입니다.

출처 : 야곰님의 swift도서