Created
December 29, 2015 12:54
-
-
Save aciidgh/9224fd0568e1bbba9cca to your computer and use it in GitHub Desktop.
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
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