swift 关键字willSet 和 didSet

// 下面是苹果给出的解释,就是在给属性设置新值的时候,可以在设置前和设置后做一些处理,这两个关键字就好像对该属性变化的监控

If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use willSet and didSet. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square.

// 代码说明

 

class man:NSObject{
    
    var isYoung:Bool
    
    var name:String = "无名氏"
    {
     
        willSet{
            
            println("will set name to \(name)")
        }
        
        didSet{
            
            println("did set name from \(oldValue) to \(name)")
        }
    }
    
    var age:Int = 0{
        willSet{
            println("Will set age to \(age)")
        }
        
        didSet{
            println("did set age from \(oldValue) to \(age)")
            if age < 18{
                isYoung = true
            }
            else{
               isYoung = false
            }
        }
    }
    // 对于未设置初始值的属性变量,创建时要初始化
    init(isyong:Bool){
        self.isYoung = isyong

        super.init()
    }
    
}

let gentleMan:man = man(isyong: false)
gentleMan.name = "张 三"
gentleMan.age = 17
gentleMan.isYoung

 

输出结果:

will set name to 无名氏
did set name from 无名氏 to 张 三
Will set age to 0
did set age from 0 to 17

 

 
 
 
posted @ 2015-03-05 10:15  狂灬的草人  阅读(404)  评论(0编辑  收藏  举报