In Swift, property observers such as
willSet
anddidSet
are not called when a property is set in an initializer. This is by design, as the initializer's purpose is to set up the initial state of an object, and during this phase, the object is not yet fully initialized. However, if we need to perform some actions similar to what we'd do in property observers during initialization, there are some workarounds.
When a Swift property has a
willSet
clause, any mutation of that property will be made on a temporary copy.⇒ At least two copies exist during the mutation.
⇒ This defeats the copy-on-write optimization for Array, String, etc. (which relies on uniquely referenced buffers).
⇒ A property of a COW type with a
willSet
will copy its contents on every mutation.Relevant for SwiftUI code because
@Published
useswillSet
: every mutation of a@Published var array: [T]
will copy the array contents.
This happens even if the willSet
doesn’t actually use the new value, e.g. if it was just being used to trigger a notification.
Previously: