Skip to content

Instantly share code, notes, and snippets.

@vfn
Created August 19, 2016 03:18
Show Gist options
  • Save vfn/da6dd79ee9c821307421b650daf642a5 to your computer and use it in GitHub Desktop.
Save vfn/da6dd79ee9c821307421b650daf642a5 to your computer and use it in GitHub Desktop.
import Foundation
// Based on http://oleb.net/blog/2015/12/lazy-properties-in-structs-swift/
final class LazyBox<T> {
init(computation: () -> T) {
self.lazyValue = .NotYetComputed(computation)
}
private var lazyValue: LazyValue<T>
private let queue = dispatch_queue_create("LazyBox.Queue.Serial", DISPATCH_QUEUE_SERIAL)
var value: T {
var value: T!
switch self.lazyValue {
case .NotYetComputed(let computation):
dispatch_sync(self.queue) {
// Check if value has been computed already in case of multi-thread access
if case .Computed(let result) = self.lazyValue {
value = result
} else {
let result = computation()
self.lazyValue = .Computed(result)
value = result
}
}
case .Computed(let result):
value = result
}
return value
}
}
private enum LazyValue<T> {
case NotYetComputed(() -> T)
case Computed(T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment