混合 Swift 属性 观察者和继承

Mixing Swift Property Observers and Inheritance

我一直在研究这个问题,我想知道是否有任何关于这个主题的文献,或者有什么方法可以知道预期的行为是什么。这是一个例子:

class A {
var paused:Bool = false {
    willSet { print("Class A willSet on paused called") }
    didSet { print("Class A didSet on paused called") }
    }
}

class B : A {
    override var paused:Bool {
        willSet { print("Class B willSet on paused called") }
        didSet { print("Class B didSet on paused called") }
    }
}

class C : B {
    override var paused:Bool {
        willSet { print("Class C willSet on paused called") }
        didSet { print("Class C didSet on paused called") }
    }
}

let testC = C()
testC.paused = true

运行时我得到这个输出:

Class C willSet on paused called Class B willSet on paused called Class A willSet on paused called Class A didSet on paused called Class B didSet on paused called Class C didSet on paused called

好像willSet是按照通常的多态方式调用的,但是didSet是倒着调用的。这有点酷,但是这种行为记录在哪里?只有这样的考试才能学吗?

didSet 调用的顺序符合预期 - 每个 child 调用它的 willSet,然后调用 super,然后调用它的 didSet。如果你通过对 super.pause 的字面调用来完成它,你会得到类似这样的东西,这使得 didSet 调用的顺序清晰:

class A {
    var paused:Bool = false

    func pause(_ paused:Bool) {
        print("Class A will set paused")
        self.paused=paused
        print("Class A did set paused")
    }
}

class B : A {
    override func pause(_ paused:Bool) {
        print("Class B will set paused")
        super.pause(paused)
        print("Class B did set paused")
    }
}

class C : B {
    override func pause(_ paused:Bool) {
        print("Class C will set paused")
        super.pause(paused)
        print("Class C did set paused")
    }
}

let testC = C()
testC.pause(true)