Skip to content

Instantly share code, notes, and snippets.

@swiftyfinch
Last active July 28, 2020 15:20
Show Gist options
  • Save swiftyfinch/a6b73ea5cace06153e9d456ff6705c4f to your computer and use it in GitHub Desktop.
Save swiftyfinch/a6b73ea5cace06153e9d456ff6705c4f to your computer and use it in GitHub Desktop.
LazyOne it's an easy implementation of default lazy keyword based on @propertyWrapper feature.
@propertyWrapper
final class LazyOnce<T> {
private var storage: T?
private let lazyBlock: () -> T
var wrappedValue: T {
if let existStorage = storage { return existStorage }
let newStorage = lazyBlock()
self.storage = newStorage
return newStorage
}
init(wrappedValue: @escaping @autoclosure () -> T) {
self.lazyBlock = wrappedValue
}
}
// Usage
final class FooBar {
lazy var foo = "Test"
// or
@LazyOnce var bar = "Test"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment