I want to do something like that: access my dictionary values with a String enumeration. I am trying to overload the subscript of the dictionary but without success.
The simplest approach is to just lift the dictionary into more context. The context in this case is "it only has keys from this enum." Lifting a type in Swift is very straightforward. Just wrap it in a struct.
// This could be a nested type inside JSONObject if you wanted.
enum JSONKeys: String {
case district
}
// Here's my JSONObject. It's much more type-safe than the dictionary,
// and it's trivial to add methods to it.
struct JSONObject {
let json: [String: AnyObject]
init(_ json: [String: AnyObject]) {
self.json = json
}
// You of course could make this generic if you wanted so that it
// didn't have to be exactly JSONKeys. And of course you could add
// a setter.
subscript(key: JSONKeys) -> AnyObject? {
return json[key.rawValue]
}
}
let address: [String: AnyObject] = ["district": "Bob"]
// Now it's easy to lift our dictionary into a "JSONObject"
let json = JSONObject(address)
// And you don't even need to include the type. Just the key.
let district = json[.district]