Skip to content

Instantly share code, notes, and snippets.

@chillpop
Last active August 8, 2022 10:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chillpop/63f399eb92be9e7c4620 to your computer and use it in GitHub Desktop.
Save chillpop/63f399eb92be9e7c4620 to your computer and use it in GitHub Desktop.
swift Dictionary subscript with String enum
protocol StringEnum {
var rawValue: String { get }
}
extension Dictionary {
subscript(enumKey: StringEnum) -> 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
}
}
}
}
//Usage:
enum JSONKey: String {
case identifier = "id"
case token
case firstName = "first_name"
case lastName = "last_name"
}
extension JSONKey: StringEnum { }
let userDict: [String: AnyObject] = [
"first_name": "Edward",
"last_name": "Gorey",
"token": "sdfkjhadfgq3894tq34tq34gq3489g",
"id": "293598346798",
]
let firstName = userDict[JSONKey.firstName]
let lastName = userDict[JSONKey.lastName]
var newUser = userDict
newUser[JSONKey.token] = "different token"
newUser[JSONKey.lastName] = "Cullen"
newUser[JSONKey.identifier] = "666"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment