gpt4 book ai didi

ios - 下标:使用 String 枚举访问我的字典值

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:12 25 4
gpt4 key购买 nike

我想做类似的事情:使用 String 枚举访问我的字典值。我试图重载字典的下标但没有成功。

访问字典:

let district = address[JsonKeys.district]

JsonKeys 在哪里:

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:不想这样做(这样可以更正错误,但是这样代码是不可读的):

let district = address[JsonKeys.district.rawValue]

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

最佳答案

最简单的方法是将字典提升到更多上下文中。这种情况下的上下文是“它只有来自这个枚举的键”。在 Swift 中提升类型非常简单。只需将其包装在一个结构中即可。

// 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]

关于ios - 下标:使用 String 枚举访问我的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39499137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com