Skip to content

Instantly share code, notes, and snippets.

@nameghino
Created August 31, 2017 16:54
Show Gist options
  • Save nameghino/6b924a931ec110e5af2710cba9e50339 to your computer and use it in GitHub Desktop.
Save nameghino/6b924a931ec110e5af2710cba9e50339 to your computer and use it in GitHub Desktop.
Dictionary extension to allow using enums (or any RawableType) as keys in a dictionary
protocol RawableKey {
associatedtype RawType
var rawValue: RawType { get }
}
extension Dictionary {
subscript<K: RawableKey>(enumKey: K) -> Value? {
get {
if let key = enumKey.rawValue as? Key {
return self[key]
}
return nil
}
set {
if let key = enumKey.rawValue as? Key {
self[key] = newValue
}
}
}
}
enum Keys: String {
case foo, bar, baz
}
extension Keys: RawableKey { }
var d = [String : Any]()
d[Keys.foo] = "foo"
d[Keys.baz] = "bar"
d[Keys.bar] = "baz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment