Skip to content

Instantly share code, notes, and snippets.

@gregomni
Created March 24, 2016 20: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 gregomni/3e6b3541e5c8428335ee to your computer and use it in GitHub Desktop.
Save gregomni/3e6b3541e5c8428335ee to your computer and use it in GitHub Desktop.
struct DefaultedDictionary<Key: Hashable, Value> {
var dict: [Key:Value]
let fallback: Value
subscript(key: Key) -> Value {
get {
return dict[key] ?? fallback
}
set {
dict[key] = newValue
}
}
}
extension Dictionary {
func defaultingTo(value: Value) -> DefaultedDictionary<Key, Value> {
return DefaultedDictionary(dict: self, fallback: value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment