Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 989
uaknight Avatar asked Apr 14 '15 05:04

uaknight


People also ask

Does didSet get called on init?

Apple's docs specify that: willSet and didSet observers are not called when a property is first initialized. They are only called when the property's value is set outside of an initialization context.

Is didSet called in init Swift?

One thing to note is that willSet and didSet will never get called on setting the initial value of the property. It will only get called whenever you set the property by assigning a new value to it. It will always get called even if you assign the same value to it multiple times.

What does didSet mean in Swift?

Observer— willSet and didSet willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.

What is didSet?

In Swift, didSet and willSet methods act as property observers. willSet runs a piece of code right before a property changes. didSet runs a piece of code right after the property has changed.


2 Answers

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.

like image 126
iyuna Avatar answered Oct 05 '22 14:10

iyuna


init() {     defer {         driver = GmDriver()     } } 
like image 44
Chiman Song Avatar answered Oct 05 '22 14:10

Chiman Song