Friday, March 3, 2023

NSViewController.ViewLoading

NSViewController.ViewLoading:

Use this property wrapper on view controller properties that can be nil before the view controller’s view loads. Wrapping view controller properties this way eliminates crashes that can occur from implicitly defining properties as Optional, and then referencing them before the view controller finishes loading.

[…]

Use this property wrapper over implicitly unwrapped optionals for IBOutlets as well.

This is introduced in the Xcode 14.3 beta but requires macOS 13.3 (still in beta) for deployment. So it will be a long time before many developers can use this, but it seems like the sort of thing you could reimplement yourself.

There are also NSWindowController.WindowLoading and UIViewController.ViewLoading.

Previously:

Update (2023-04-22): Daniel Jalkut:

MagicLoading is a reference implementation of a @ViewLoading-style property wrapper.

[…]

The magic in Apple’s wrappers is an under-documented but widely used alternative mechanism for property wrappers: the ability to define getters and setters with knowledge of the containing object’s type, and access to the specific instance. The “subscript” variant of property wrappers is described in the original proposal, but has never been publicly endorsed, as far as I know, by Apple or the Swift team.

Usually I would shy away from undocumented features, but in this situation I believe it’s safe to use the undocumented subscript functionality because doing so only instructs the compiler to generate wrapper code that is compiled into the resulting binary. In other words: there are no private runtime dependencies that are being assumed by opting into this more sophisticated form of property wrapper.

So it shouldn’t count as private API for the App Store. I guess the main danger is that future versions of the compiler could remove support for this feature. Hopefully they will instead replace it with an official feature that’s more ergonomic.

1 Comment RSS · Twitter · Mastodon

These property wrappers can't be back-deployed because a property wrapper is a type, and types cannot be back-deployed (at least not without major effort).

When Swift gets accessor macros, it'll be possible to implement something like ViewLoading with a macro. The macro expansion won't need to call any new API, so it will back-deploy.

Leave a Comment