Wednesday, December 20, 2023

Triggering Swift Property Observers From Initializers

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.


5 Comments RSS · Twitter · Mastodon

Please don’t link to twitter posts that aren’t public.

@sirshannon That was not my intent. I’m not sure what happened here. I know the post was public at the time I saved the text because I used Nitter. The account was active yesterday when I drafted the post and checked the links, but now everything seems to be deleted or hidden from me.

The tweet is still there, Ole just set his account to private for whatever reason. That should be forbidden regardless of whatever temper tantrum a user is going through. Any public post should remain public, or explicitly deleted by the user, and then new posts should be private.

Regarding this story, wow. So many ridiculous gotchas with Swift and SwiftUI. Remember when all the Swift clowns claimed Cocoa bindings were too slow and too convoluted to bring to the phone and shouldn’t be used on Mac? Oh yeah, the SwiftUI story is so much performant and clear of any convolution.

@Leo Now I’m seeing that Begemann’s tweet is visible again but that his account is private, whereas earlier today I couldn’t see it at all. Also, earlier today the link to the Eidhof tweet was broken, but now it’s working again (and his account is not private). So I’m not sure whether they are repeatedly changing their privacy settings or whether this is just random Twitter brokenness.

I think it’s a bug that you are able to see the content. It seems Ole set his account to private last year, when he left for Mastodon.

Leave a Comment