Skip to content

Instantly share code, notes, and snippets.

@gregomni
Created March 24, 2016 21:57
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/405601215df8c9ca506c to your computer and use it in GitHub Desktop.
Save gregomni/405601215df8c9ca506c to your computer and use it in GitHub Desktop.
protocol Fallbackable {
associatedtype Value
static var fallback: Value { get }
}
struct DefaultDict<K: Hashable, V, F: Fallbackable where V == F.Value> {
var dict: [K:V]
subscript(key: K) -> V {
get {
return dict[key] ?? F.fallback
}
set {
dict[key] = newValue
}
}
}
extension Dictionary {
func defaulting<F: Fallbackable where Value == F.Value>(f: F.Type) -> DefaultDict<Key, Value, F> {
return DefaultDict<Key, Value, F>(dict: self)
}
}
struct IntZero : Fallbackable {
static var fallback: Int { return 0 }
}
let dict = ["x": 3, "y": 4]
let dd = dict.defaulting(IntZero.self)
dd["x"] // 3
dd["y"] // 4
dd["z"] // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment