Subscript: access my dictionary values with a String enumeration

前端 未结 3 637
隐瞒了意图╮
隐瞒了意图╮ 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:36

    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"
    

提交回复
热议问题