Skip to content

Instantly share code, notes, and snippets.

@AlexChekel1337
Created June 11, 2024 14:56
Show Gist options
  • Save AlexChekel1337/7cd8476910f5205af3c2cd266c8bdf4e to your computer and use it in GitHub Desktop.
Save AlexChekel1337/7cd8476910f5205af3c2cd266c8bdf4e to your computer and use it in GitHub Desktop.
A backport of @ViewLoading property wrapper from iOS 16.4
extension UIViewController {
/// A property wrapper that loads the view controller’s view before accessing the property.
/// A backport of `@ViewLoading` property wrapper, available in iOS 16.4.
/// https://developer.apple.com/documentation/uikit/uiviewcontroller/viewloading
@propertyWrapper
struct ViewLoader<Value> {
static subscript<T: UIViewController>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value {
get {
instance.loadViewIfNeeded()
return instance[keyPath: storageKeyPath].storage
}
set {
instance[keyPath: storageKeyPath].storage = newValue
}
}
@available(*, unavailable)
var wrappedValue: Value {
get { fatalError() }
set { fatalError() }
}
private var storage: Value!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment