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.
Try this:
extension Dictionary where Key: StringLiteralConvertible {
subscript(index: JsonKeys) -> Value {
get {
return self[index.rawValue as! Key]!
}
}
}
Remember, with having constraint as Key: StringLiteralConvertible
, the extension works for any Dictionaries with its Key conforming to StringLiteralConvertible
. (You know many types other than String
conform to StringLiteralConvertible
.)
To call subscript self[]
, you need to pass a value of type Key
. index.rawValue
is String
, which may not always be a Key
in the extension.
So, the extension I have shown would work for some Dictionaries, would cause runtime crash for some other Dictionaries.
A little bit more type-safe way:
protocol MyJsonKeysConvertible {
init(jsonKeys: JsonKeys)
}
extension String: MyJsonKeysConvertible {
init(jsonKeys: JsonKeys) {self = jsonKeys.rawValue}
}
extension Dictionary where Key: MyJsonKeysConvertible {
subscript(index: JsonKeys) -> Value {
get {
return self[Key(jsonKeys: index)]!
}
}
}