LoginSignup
1
1

More than 5 years have passed since last update.

Swift - 观察者模式(属性监听)

Posted at
//  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)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1