前端之家收集整理的这篇文章主要介绍了
Swift语言中用了willSet和didSet,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Swift语言中用了willSet和didSet这两个特性来监视
属性的除初始化之外的
属性值变化 import Foundation class People : NSObject { //普通
属性 var name1:String = "" var lastName:String = "" var nickName:String = "" //计算
属性 var fullName:String { get { return nickName + " " + name1 + " " + 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 */