Skip to content

Instantly share code, notes, and snippets.

@aciidgh
Created December 29, 2015 12:54
Show Gist options
  • Save aciidgh/9224fd0568e1bbba9cca to your computer and use it in GitHub Desktop.
Save aciidgh/9224fd0568e1bbba9cca to your computer and use it in GitHub Desktop.
struct LazyStore<Key: Hashable, Value> {
private var store: [Key : Value] = [:]
let builderClosure: Key -> Value?
init(builderClosure: Key -> Value?) {
self.builderClosure = builderClosure
}
private mutating func insertIfNeeded(key: Key) {
guard store[key] == nil else {
return
}
store[key] = builderClosure(key)
}
mutating func addObjectForKey(key: Key) {
insertIfNeeded(key)
}
mutating func valueForKey(key: Key) -> Value? {
insertIfNeeded(key)
return store[key]
}
}
var myStore = LazyStore<String, Int> { $0.hashValue }
myStore.valueForKey("Hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment