6

我正在尝试解析以下 JSON:

{ 
  "String For Key 1": [
    "Some String A",
    "Some String B",
    "Some String C",
  ],
  "String For Key 2": [
    "Some String D",
    "Some String E",
    "Some String F"
  ],
  "String For Key 3": [
    "Some String G",
    "Some String H",
    "Some String I",
  ],
  "String For Key 4": [
    "Some String J",
    "Some String K",
    "Some String L"
  ],
  "String For Key 5": [
    "Some String M",
    "Some String N",
    "Some String O"
  ],
  "String For Key 6": [
    "Some String P",
    "Some String Q",
    "Some String R"
  ]
}

我也在关注本教程。它在 Playground 的 Github 上

在示例中,他们正在Array使用typealias JSONDictionary = [String: AnyObject]

我需要解析一个Dictionary具有Key哪个是的StringValue那是一个Array。因此:typealias JSONDictionary = [String: [AnyObject]]并且在返回flatMap.

extension Resource {
    init(url: NSURL, parseJSON: AnyObject -> A?) {
        self.url = url
        self.parse = { data in
            let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: [AnyObject]]
           //This is where I get an error
            return json.flatMap(parseJSON)
        }
    }
}

错误:

Cannot convert value of type `AnyObject -> A? to expected argument type `([String: [AnyObject]]?) -> _?

如何获得带有KeysasStringValuesas an的字典Array?我想保持他们的Generic做法。

4

1 回答 1

6

jsonString 的类型是Dictionary<String, Array<String>> 你可以给它一个类型Dictionary<String, AnyObject>

AnyObject 可以包含类和结构,即Array, Dictionary, String, Int, Obj C 类因此 anArray<String>AnyObject not表示 [AnyObject]

let jsonString:[String: AnyObject] =
[
    "String For Key 1": [
    "http://www.urlToSomePathA.jpg",
    "http://www.urlToSomePathB.jpg",
    "http://www.urlToSomePathC.jpg",
    ],
    "String For Key 2": [
    "http://www.urlToSomePathD.jpg",
    "http://www.urlToSomePathE.jpg",
    "http://www.urlToSomePathF.jpg"
    ]
]

// Now you can map a function on the value type
let values = jsonString.flatMap { $0.1 as? [String] }
print(values)
// RESULT: [["http://www.urlToSomePathA.jpg", "http://www.urlToSomePathB.jpg", "http://www.urlToSomePathC.jpg"], ["http://www.urlToSomePathD.jpg", "http://www.urlToSomePathE.jpg", "http://www.urlToSomePathF.jpg"]]

更新

let keys = jsonString.flatMap { $0.0 } // ["String For Key 1", "String For Key 2"]

正如@dffri 评论的那样,您可以在字典上使用 keys 属性,该属性将返回LazyMapCollection,只有当您访问其中的对象时才会实现。

let keys = jsonString.keys
于 2016-08-07T06:04:17.450 回答