Created
April 22, 2020 08:04
-
-
Save douglashill/accde7f3db06b33a37f1389e32d293b1 to your computer and use it in GitHub Desktop.
A Swift property wrapper that implements ‘lazy let’. I.e. a read-only property that loads its value when first read. Not safe for access from multiple threads.
This file contains 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
/// A Swift property wrapper that implements ‘lazy let’. I.e. a read-only property that loads its value when first read. | |
/// Not safe for access from multiple threads. | |
/// Does not work the same as the lazy keyboard because the property initialiser will run before self is available. | |
/// Adapted from https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md | |
@propertyWrapper enum LazyLet<Value> { | |
case uninitialised(() -> Value) | |
case initialised(Value) | |
init(wrappedValue: @autoclosure @escaping () -> Value) { | |
self = .uninitialised(wrappedValue) | |
} | |
var wrappedValue: Value { | |
mutating get { | |
switch self { | |
case .uninitialised(let initialiser): | |
let value = initialiser() | |
self = .initialised(value) | |
return value | |
case .initialised(let value): | |
return value | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about using a class instead? The following one should solve your case: