You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Clarify property observer behavior during initialization (#370)
The first sentence on superclass behavior is true, but the final
sentence on same-class behavior is misleading. Property observers are
not triggered regardless of whether the superclass initializer has been
called or not. However, a mutating function called from the initializer
_does_ trigger property observers. Personally I think this is
counterintuitive, the topic has been discussed in the Swift Forum [1]
and would probably be a headache for the compiler and isn't going to
change anyway (in order to preserve the semantics of existing code). But
the fact remains that the superclass initializer is a red herring in the
final sentence.
[1] https://forums.swift.org/t/14024/1
Tested with Xcode 16.3, Swift 6.1.
```
import Foundation
class Ship {
var crewSize: Int {
willSet { print("Ship: willSet crewSize to", newValue) }
didSet { print("Ship: didSet crewSize to", crewSize) }
}
init(crewSize: Int) {
self.crewSize = crewSize
}
}
class CargoShip: Ship {
var cargoCapacity: Int {
willSet { print("CargoShip: willSet cargoCapacity to", newValue) }
didSet { print("CargoShip: didSet cargoCapacity to", cargoCapacity) }
}
init(cargoCapacity: Int, crewSize: Int) {
self.cargoCapacity = cargoCapacity
super.init(crewSize: crewSize)
// Instance is now fully initialized.
// Change a property in the superclass, property observers are called
// as expected.
self.crewSize += 5
// Change a property in the class after the superclass has been
// initialized, property observers are not called (?)
self.cargoCapacity += 20
// But call a function that changes a property in the class, property
// observers are called (??)
doubleCargoCapacity()
}
func doubleCargoCapacity() {
cargoCapacity *= 2
}
}
let cargoShip = CargoShip(cargoCapacity: 10, crewSize: 5)
// Ship: willSet crewSize to 10
// Ship: didSet crewSize to 10
// CargoShip: willSet cargoCapacity to 60 (triggered by doubleCargoCapacity)
// CargoShip: didSet cargoCapacity to 60 (triggered by doubleCargoCapacity)
```
0 commit comments