Last active
July 28, 2020 15:20
-
-
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.
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
@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