Skip to content

Instantly share code, notes, and snippets.

@el-hoshino
Created March 5, 2018 07:45
Show Gist options
  • Save el-hoshino/52d0e9776fb24f9ce8fd2f9497e597d3 to your computer and use it in GitHub Desktop.
Save el-hoshino/52d0e9776fb24f9ce8fd2f9497e597d3 to your computer and use it in GitHub Desktop.
Declaring a lazy-initialized object with `let` in Swift
class Lazy <T> {
private var t: T?
private let initializer: () -> T
private let semaphore = DispatchSemaphore(value: 1)
init(_ initializer: @escaping () -> T) {
self.initializer = initializer
}
private func initialize() -> T {
return self.initializer()
}
var value: T {
self.semaphore.wait()
defer { self.semaphore.signal() }
switch self.t {
case .some(let t):
return t
case .none:
let t = initialize()
defer { self.t = t }
return t
}
}
}
func lazy <T> (_ initializer: @escaping () -> T) -> Lazy<T> {
return Lazy(initializer)
}
struct A {
let i: Int
}
class Test {
let a: Lazy<A> = lazy { A(i: 1) }
}
let test = Test()
test.a.value.i // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment