在调用 super.init 之前未调用 Swift 变量观察器

标签 swift observers didset

好吧,我正在阅读有关如何在 swift 中使用 willSet/didSet 的内容,我发现了一个关于 apples swift 文档的注释,它对我来说没有任何意义,我希望有人能解释一下。这是注释:

The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.

发件人:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

让我感到困惑的是,他们指出在 B 对 A 调用 super.init 之前,并没有调用子类 B 中父类(super class) A 属性的观察者。

class A {
    var p: Bool

    init() {
        p = false
    }
}

class B: A {

    override var p: Bool {
        didSet {
            print("didSet p")
        }
    }

    override init() {
        p = true // Compiler error
        super.init()
    }
}

然而,在那段时间 A 或 B 都无法访问该属性,所以无论如何谁会调用观察员?尝试读取/写入该属性甚至会导致编译器错误,因此在 Swift 中甚至不可能错误地执行此操作。我是不是遗漏了什么,或者这只是指出错误内容的误导性说明?

最佳答案

他们正在谈论以下场景:

class A {
    var p: Bool {
        didSet {
            print(">>> didSet p to \(p)")
        }
    }

    init() {
        p = false // here didSet won't be called
    }
}

class B: A {

    override init() {
        // here you could set B's properties, but not those inherited, only after super.init()
        super.init()
        p = true // here didSet will be called
    }
}

B()

它将打印如下:

>>> didSet p to true

虽然对您来说这似乎很自然,但文档必须明确记录此行为。

关于在调用 super.init 之前未调用 Swift 变量观察器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391886/

相关文章:

ios - 如何正确使用 Core Data managedObjectContext 以及保存上下文的正确方法?

ios - Master Detail View 我想回到主视图而不是详细 View

ios - 调用中的额外参数 "method"。阿拉莫菲尔

SWIFT - 防止同时调用相同的函数

javascript - polymer :用复杂的观察器观察阵列突变

ios - FirebaseDatabase - removeAllObservers() - 它实际上删除了什么?

ios - 如何在自定义单元格中使用其他 didSet 变量的首选项?

ios - 当其中一个属性发生变化时,监听数据模型数组中的更新

activerecord - 为多个模型动态实例化 ActiveRecord Observer

Swift - didSet 中的弱 self