Swift中的willSet與didSet

周銀輝發表於2014-06-23

                Swift中的willSet與didSet

                    周銀輝

 

在Swift語言中用了willSet和didSet這兩個特性來監視屬性的除初始化之外的屬性值變化

無需說太多,看看下面的程式碼你就能很快明白的

import Foundation


class People : NSObject
{
    //普通屬性
    var firstName:String = ""
    var lastName:String  = ""
    var nickName:String  = ""
    
    //計算屬性
    var fullName:String
    {
        get
        {
            return nickName + " " + firstName + " " + lastName
        }
    }
    
    //帶屬性監視器的普通屬性
    var age:Int = 0
    {
        //我們需要在age屬性變化前做點什麼
        willSet
        {
            println("Will set an new value \(newValue) to age")
        }
        //我們需要在age屬性發生變化後,更新一下nickName這個屬性
        didSet
        {
            println("age filed changed form \(oldValue) to \(age)")
            if age<10
            {
                nickName = "Little"
            }else
            {
                nickName = "Big"
            }
        }
    }
    
    func toString() -> String
    {
        return "Full Name: \(fullName) " + ", Age: \(age) "
    }
    
}

var me = People()
me.firstName = "Zhang"
me.lastName  = "San"
me.age = 20

println(me.toString())

/*程式輸出
Will set an new value 20 to age
age filed changed form 0 to 20
Full Name: Big Zhang San , Age: 20
*/

 

 

相關文章