在 swift 中遍历字典

Traversing a dictionary in swift

我是 swift 的新手,正在尝试调用结果为 JSON 数据的 Web 服务。它的结构如下:

{
  temp : [
        {
           key1:value1
           key2:value2
           key3:value3
        }
        {
           key1:value1
           key2:value2
           key3:value3
        }
        {
           key1:value1
           key2:value2
           key3:value3
        }
      ]
}

我能够得到结果JSON。但是我怎么遍历这个Dictionary。我想显示所有字典中的 value2。

任何帮助将不胜感激

提前致谢

像这样:

let dictArray:[[String:String]] = [["k1":"v1" ,"k2":"v2", "k3":"v3"],     ["k1":"v1" ,"k2":"v2", "k3":"v3"]]
for dict in dictArray {
  for (key, val) in dict {
    if val == "v2" {
      println(key)
    }
  }
}

我猜你更想获得一个键的值,但你的问题有点误导。

假设这是我的本地 json 文件:

Json 文件:

   {
  "temp" : [
            {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
            },
            {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
            },
            {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
            }
            ]
}

用于解析 JSON 和打印 "key2"

值的代码
var error: NSError?

   // get json data from local json file
    let jsonFilePath = NSBundle.mainBundle().pathForResource("MyFile", ofType: "json")!
    let jsonData = NSData(contentsOfFile: jsonFilePath)!


    let jsonObjects: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error)

    let items: NSArray! = jsonObjects["temp"] as? NSArray

    for index in 0...items.count - 1  {
      let item = items[index] as NSDictionary
      println(item["key2"]!);
    }

一些有用的链接:

Dictionary documentation

NSDictionary documentation

Working with JSON in Swift

祝你好运