Swift中的willSet與didSet

                Swift中的willSet與didSetspa

                    周銀輝code

 

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

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

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
*/
相關文章
相關標籤/搜索