美文网首页
willSet和didSet的区别

willSet和didSet的区别

作者: 歌手的剑 | 来源:发表于2017-03-20 10:16 被阅读12次

    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)")ifage<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=20println(me.toString())/*程序输出

    Will set an new value 20 to age

    age filed changed form 0 to 20

    Full Name: Big Zhang San , Age: 20*/

    相关文章

      网友评论

          本文标题:willSet和didSet的区别

          本文链接:https://www.haomeiwen.com/subject/zkebnttx.html