47

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?

uaknight
  • 685
  • 1
  • 6
  • 11
  • 15
    Property observers are not called during init, see http://stackoverflow.com/questions/25230780/is-it-possible-to-allow-didset-to-be-called-during-initialization-in-swift – Martin R Apr 14 '15 at 05:42
  • 2
    Thanks! Missing both Apple's documentation and searching stackoverflow really should earn me minus reputation... – uaknight Apr 14 '15 at 07:09
  • @MartinR please add that as an answer, maybe? – Dan Rosenstark Apr 08 '16 at 01:29
  • 1
    Possible duplicate of [Is it possible to allow didSet to be called during initialization in Swift?](http://stackoverflow.com/questions/25230780/is-it-possible-to-allow-didset-to-be-called-during-initialization-in-swift) – Cœur Mar 23 '17 at 02:10

2 Answers2

51

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.

iyuna
  • 1,787
  • 20
  • 24
3
init() {
    defer {
        driver = GmDriver()
    }
}
Chiman Song
  • 141
  • 10