Skip to content

Instantly share code, notes, and snippets.

@daehn
Created October 5, 2017 09:38
Show Gist options
  • 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