Last active
October 25, 2018 17:18
-
-
Save robtimp/e167c25310fd240aaef66beeadcb604f to your computer and use it in GitHub Desktop.
EnumDictionary
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
struct EnumDictionary<Key: Hashable & CaseIterable, Value> { | |
private let dictionary: [Key: Value] | |
init(_ dictionary: [Key: Value]) { | |
for key in Key.allCases { | |
assert(dictionary[key] != nil, "All enum cases must be assigned a value.") | |
} | |
self.dictionary = dictionary | |
} | |
subscript(_ key: Key) -> Value { | |
return dictionary[key]! | |
} | |
} | |
extension EnumDictionary: ExpressibleByDictionaryLiteral { | |
init(dictionaryLiteral elements: (Key, Value)...) { | |
var dictionary = [Key: Value]() | |
elements.forEach { | |
dictionary[$0.0] = $0.1 | |
} | |
self.init(dictionary) | |
} | |
} | |
enum Thing: CaseIterable { | |
case this | |
case that | |
case theOther | |
} | |
let x: [Thing: Int] = [.this: 5, .that: 42, .theOther: -8] | |
let y = EnumDictionary(x) | |
y[.this] // 5 (Non-optional, since we've already determined every enum key has a value) | |
let z: EnumDictionary = [Thing.this: "A", .that: "B", .theOther: "C"] | |
z[.theOther] // C (Non-optional) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment