willset didset 属性观察器

在属性的各个时间节点来做相应的处理

var variable1 : Int = 0 {
        //variable1变量变化前 运行
        willSet/*(newValue)*/{
            print("willSet called")
            print("we will set \(newValue) to variable1")
        }
//variable1 变化后 运行
  didSet
{ print("didSet called")
print("variable1 is changed from \(oldValue) to \(variable1)")
 } } print("we are going to add 3") variable1 = 3 print("we have been added 3")


output

we are going to add 3
willSet called
we will set 3 to variable1
didSet called
variable1 is changed from 0 to 3
we have been added 3


another sample


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
*/


var title: NSString {
   get {
    return super.title
  }
  set {
    super.title = newValue
  }
  didSet {
     println("test override property")
  }
}



更多推荐