如何通过索引打印JSON Dictionary元素?

时间:2016-04-14 20:20:22

标签: ios json swift

我写了下一个片段:

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! Dictionary<String, AnyObject>

    for i in 0...json.count - 1 {
        print(json[i]["title"])
     }
} catch let error as NSError {
    print(error)
}

在这种情况下我收到错误:

Cannot subscript a value of type 'Dictionary<String, AnyObject>' with an index of type 'Int'

我想按索引获取元素。我一直与Alamofire合作,但今天我想默认做所有这些。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您的json是字典(Dictionary<String, AnyObject>)如果要迭代字典,则应使用以下语法:

for (someString, someAnyObject) in json {
    print(someString, someAnyObject)
}

了解更多here