Last active
August 11, 2024 03:32
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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