Skip to content

Instantly share code, notes, and snippets.

@pixyzehn
Forked from JohnSundell/Autoclosure.swift
Created January 21, 2017 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixyzehn/f1dd832ffd068552d6bf4bf3e5251c33 to your computer and use it in GitHub Desktop.
Save pixyzehn/f1dd832ffd068552d6bf4bf3e5251c33 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