// Created by Kxx.xxQ 一生相伴 on 16/2/22.
// Copyright © 2016年 Asahi_Kuang. All rights reserved.
//
import Foundation
// Swift-观察者模式(属性监听),当给对象的属性赋值时,可以用willSet和didSet进行对象属性值变化的观察。
// willSet表示属性即将改变通知回调方法,didSet表示属性已经改变通知回调方法。
// warning!: 观察者模式不能用于懒加载的类属性。
class student {
var stuName: String = "" {
willSet {
print("姓名即将修改,新值为:\(newValue)")
}
didSet {
print("姓名已经修改,旧值为:\(oldValue)")
}
}
var stuID: String = "" {
willSet {
print("学号即将修改,新值为:\(newValue)")
}
didSet {
print("学号已经修改,旧值为:\(oldValue)")
}
}
init(name: String, id: String) {
stuName = name
stuID = id
}
}
let stu = student(name: "邝清旭", id: "20161991")
print(stu.stuName," ", stu.stuID)
stu.stuName = "夏小秋"
stu.stuID = "20161993"
print(stu.stuName," ", stu.stuID)
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
11