uaknight
uaknight

Reputation: 695

In Swift, didSet doesn’t fire when invoked from init()

I’ve got a car and a driver. They mutually reference each other. In the car’s init() I create a driver and assign it to the driver member. The driver member has a didSet method which is supposed to set the driver’s car, thus mutually link them to each other.

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

However, the didSet never fires. Why?

Upvotes: 48

Views: 13058

Answers (2)

Chiman Song
Chiman Song

Reputation: 161

init() {
    defer {
        driver = GmDriver()
    }
}

Upvotes: 3

iyuna
iyuna

Reputation: 1797

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.

Upvotes: 52

Related Questions