Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Created January 19, 2017 15:00
Show Gist options
  • Save JohnSundell/ba51a340235c5116a5902fa83997fb71 to your computer and use it in GitHub Desktop.
Save JohnSundell/ba51a340235c5116a5902fa83997fb71 to your computer and use it in GitHub Desktop.
Simple Dictionary extension to avoid the if let-dance when retrieving values
extension Dictionary {
mutating func value(for key: Key, orAdd closure: @autoclosure () -> Value) -> Value {
if let value = self[key] {
return value
}
let value = closure()
self[key] = value
return value
}
}
// Usage:
var colors = [
"red" : UIColor.red
]
// Blue will be added, since it's missing from `colors`
let blue = colors.value(for: "blue", orAdd: UIColor.blue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment