Subscript: access my dictionary values with a String enumeration

前端 未结 3 609
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 16:14

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.

3条回答
  •  生来不讨喜
    2021-01-03 16:42

    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)]!
            }
        }
    }
    

提交回复
热议问题