Skip to content

willSet, didSet

Ken Harris edited this page Feb 1, 2019 · 1 revision

Swift has didSet and willSet observers.

The documentation implies that they will be run in an init after super.init() (i.e., once self exists), but this is a lie. All property assignments in init, even non-initial assignments, bypass observers. (You may be able to work around this with defer, but they say that's a bug which will be fixed in the future, so don't count on it.) Simpler rule: never do an initial property assignment in an initializer for a property with an observer. Just give it a default value (empty array, enum rawValue 0, whatever), and then make the caller assign it in a separate step. It will save hours of grief.

TODO: bug#'s for these

Clone this wiki locally