Created
August 19, 2016 03:18
-
-
Save vfn/da6dd79ee9c821307421b650daf642a5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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