Backporting @ViewLoading property wrapper to older iOS versions

Backporting @ViewLoading property wrapper to older iOS versions

Alexander Chekel

While watching this year's "What's new in UIKit" session, an unfamiliar expression in the slide caught my attention.

A slide from "What's new in UIKit" WWDC 2024 session

I've noticed a @ViewLoading property wrapper I haven't seen before attached to the feedbackGenerator property declaration, and I quickly rushed to developer documentation looking for it. Turns out it was quietly added in iOS 16.4 and due to its simplicity it didn't make it to the last year's "What's new in UIKit" session.

What's it for?

Basically it ensures that view controller's view is loaded at the time of accessing a property, marked with @ViewLoading wrapper. In the slide above, UICanvasFeedbackGenerator requires a view passed as an argument to its initializer, so instead of delaying its initialization with lazy var declaration, presenter makes use of this new property wrapper. As you can see, there are no optionals or explicitly unwrapped optionals, and as Apple suggests in the documentation, you should use it together with @IBOutlet when prototyping UI in Interface Builder:

class ViewController: UIViewController {
    @IBOutlet @ViewLoading private var textLabel: UILabel
}

Backporting

Unfortunately, this property wrapper is only available starting from iOS 16.4, and some of my apps still require at least iOS 15.0, so I tried implementing it myself.

My implementation (and I'm sure Apple's too) utilizes property wrapper subscript mechanism to access its enclosing object. Here's what I quickly threw together:

This extension is available as a gist.

Report Page