Skip to content

Instantly share code, notes, and snippets.

@robtimp
Last active October 25, 2018 17:18
Show Gist options
  • Save robtimp/e167c25310fd240aaef66beeadcb604f to your computer and use it in GitHub Desktop.
Save robtimp/e167c25310fd240aaef66beeadcb604f to your computer and use it in GitHub Desktop.
EnumDictionary
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