Last active
August 8, 2022 10:12
-
-
Save chillpop/63f399eb92be9e7c4620 to your computer and use it in GitHub Desktop.
swift Dictionary subscript with String enum
This file contains hidden or 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 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