Quantcast
Channel: December 2023 – Michael Tsai
Viewing all articles
Browse latest Browse all 85

Triggering Swift Property Observers From Initializers

$
0
0

Natalia Panferova:

In Swift, property observers such as willSet and didSet 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.

Ole Begemann:

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 uses willSet: 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:


Viewing all articles
Browse latest Browse all 85

Trending Articles