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

Swift中的willSet与didSet

时间:2016-01-08 14:38:40      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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

Swift中的willSet与didSet

标签:

原文地址:http://www.cnblogs.com/liaolijun/p/5113114.html

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