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?
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.
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.
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.
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.
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.
init() { defer { driver = GmDriver() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With