swift - 在 Swift 中,从 init() 调用时 didSet 不会触发

标签 swift

我有车和司机。他们相互引用。在汽车的 init() 中,我创建了一个驱动程序并将其分配给驱动程序成员。 driver 成员有一个 didSet 方法,该方法应该设置司机的车,从而将它们相互链接起来。

class GmDriver {
    var car: GmCar! = nil
}

class GmCar {
    var driver: GmDriver {
        didSet {
            driver.car = self
        }
    }
    init() {
        driver = GmDriver()
    }
}

let myCar = GmCar()
println(myCar.driver.car) // nil

但是,didSet 永远不会触发。为什么?

最佳答案

Apple Documentation :

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.

关于swift - 在 Swift 中,从 init() 调用时 didSet 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29619846/

相关文章:

ios - Swift - 强制从库和相机中获取方形照片

iOS保存标签数据

ios - 自动完成文本字段和 Firebase

ios - 为什么 CoreLocation 无法获取新的 GPS 数据而 Mapkit 显示旧的 GPS 数据

ios - 我的通话错误 : Incorrect Argument Label In Call (have 'key:' , 预期为 'coder:' )

ios - 如何阻止 iOS 在执行关键操作时终止应用程序?

swift - 对成员 "text"的模糊引用

ios - 为什么 Slides[i].frame 打印的值与 SlideScrollView.subviews[i].frame 不同

arrays - 如何在多个数组的索引处保存多个元素?

ios - 枚举元素不能作为实例成员引用