Created
November 7, 2017 20:14
-
-
Save gregomni/cb0ce2d5008006038e4e6b9c2b130666 to your computer and use it in GitHub Desktop.
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
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>(_ 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 | |
struct EmptyArray<Element>: Fallbackable { | |
static var fallback: [Element] { return [] } | |
} | |
var d2: [String: [Int]] = [:] | |
var d2d = d2.defaulting(EmptyArray.self) | |
d2d["a"].append(3) | |
d2d // "a":[3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment