Created
January 19, 2017 15:00
-
-
Save JohnSundell/ba51a340235c5116a5902fa83997fb71 to your computer and use it in GitHub Desktop.
Simple Dictionary extension to avoid the if let-dance when retrieving values
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
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