swift中的willSet与didSet
今天学到了iOS动态界面布局,里面正好涉及到了swift中didSet和willSet的代码。
就上网搜索了一下,找到一篇博文里面写得特别简单易懂,就顺手拷贝了过来。
原文地址如下:Swift中的willSet与didSet
下面是我原封不动拷贝来的代码,用于备忘。
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 */
** Then I looked up at the sky and saw the sun **
posted on 2016-03-29 13:34 chenyangsocool 阅读(251) 评论(0) 编辑 收藏 举报