Skip to content

Instantly share code, notes, and snippets.

@daehn
Created October 5, 2017 09:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daehn/3632a2e6eeb7461ce8efa1e5fae22da1 to your computer and use it in GitHub Desktop.
Save daehn/3632a2e6eeb7461ce8efa1e5fae22da1 to your computer and use it in GitHub Desktop.
Subscript a dictionary with an enum having a matching rawValue type without having to use .rawValue after the case
extension Dictionary {
subscript<T: RawRepresentable>(_ key: T) -> Value? where T.RawValue == Key {
return self[key.rawValue]
}
}
// Usage:
enum Type: Int {
case easy
}
enum Key: String {
case label
}
let types = [0: "🎉"]
types[Type.easy] // "🎉"
let info = ["label": "💥"]
info[Key.label] // "💥"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment