码迷,mamicode.com
首页 > 编程语言 > 详细

swift 关键字willSet 和 didSet

时间:2015-03-05 10:34:45      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

 
 
 

swift 关键字willSet 和 didSet

标签:

原文地址:http://www.cnblogs.com/Alex-798-Dcr/p/4315043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!