Created
August 31, 2017 16:54
-
-
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
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 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