下标:使用String枚举访问我的字典值 [英] Subscript: access my dictionary values with a String enumeration

查看:247
本文介绍了下标:使用String枚举访问我的字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样做:使用String枚举访问我的字典值。我试图重载字典的下标,但没有成功。

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.

访问字典:

let district = address[JsonKeys.district]

其中JsonKeys是: / p>

where JsonKeys is:

enum JsonKeys: String {
    case key1
    case key2
    case key...
}

,我的下标重载如下:

extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
    subscript(index: FOJsonKeys) -> AnyObject {
        get {
            return self[ index.rawValue] as! AnyObject
        }
    }
}

我收到以下消息:

**Cannot subscript a value of type 'Dictionary<Key, Value>' with an index of type 'String'**

我错了什么?

PS:不想这样做(这将纠正错误,但代码不可读这种方式):

PS: don't want to do this (this would correct the error, but the code is unreadable this way):

let district = address[JsonKeys.district.rawValue]

字典是Json解析了AlamoFire给我的字典。我很确定我不能改变它的类型。

The dictionary is a Json parsed dictionary given to me by AlamoFire. I am pretty sure I can't change its type.

推荐答案

最简单的方法是将字典提升到更多的上下文中。这种情况下的上下文是它只有这个枚举的密钥。在Swift中提起一个类型非常简单。只需将它包装在一个结构体中。

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]

这篇关于下标:使用String枚举访问我的字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆