Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Created July 16, 2024 21:22
Show Gist options
  • Save drewolbrich/61119607d1974fd40f50a4f7975af84d to your computer and use it in GitHub Desktop.
Save drewolbrich/61119607d1974fd40f50a4f7975af84d to your computer and use it in GitHub Desktop.
/// An async-safe lazy variable wrapper, possibly suitable for using with global
/// variables in Swift 6.
///
/// From https://developer.apple.com/documentation/realitykit/rendering-a-windowed-game-in-stereo
actor LazyAsync<T: Sendable> {
private var value: T?
private let closure: () async -> T
init(_ closure: @escaping () async -> T) {
self.closure = closure
}
func get() async -> T {
if let value {
return value
} else {
self.value = await closure ()
return await get()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment