Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.
//  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)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした