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.
I know that this is an old question, but I'd thought I'd add an implementation that is easier to extend, reuse, and more lightweight
public protocol UsesRawValue {
var rawValue: String { get }
}
extension JsonKeys: UsesRawValue {}
extension Dictionary where Key: ExpressibleByStringLiteral {
public subscript(key: UsesRawValue) -> Value? {
get { return self[key.rawValue as! Key] }
set { self[key.rawValue as! Key] = newValue }
}
}
Based on this blog post
This approach only requires us to extend our dictionary once, rather than for each enum. Instead, each enum needs to conform to UsesRawValue. Now we can use it like this.
ajson[JsonKeys.key1]
ajson[JsonKeys.key1] = "name"