Swift 3访问json feed中的嵌套字典

时间:2016-11-16 10:54:03

标签: arrays json swift dictionary swift3

您好我目前有一个JSON Feed:

"hourly":{  
      "summary":"Breezy and partly cloudy tomorrow morning.",
      "icon":"wind",
      "data":[  
         {  
            "time":1479222000,
            "summary":"Clear",
            "icon":"clear-night",
            "precipIntensity":0,
            "precipProbability":0,
            "temperature":25.09,
            "apparentTemperature":25.09,
            "dewPoint":21.56,
            "humidity":0.81,
            "windSpeed":1.13,
            "windBearing":72,
            "visibility":9,
            "cloudCover":0.1,
            "pressure":1015.18,
            "ozone":242.43
         },
         {  
            "time":1479225600,
            "summary":"Clear",
            "icon":"clear-night",
            "precipIntensity":0,
            "precipProbability":0,
            "temperature":24.18,
            "apparentTemperature":24.18,
            "dewPoint":20.71,
            "humidity":0.81,
            "windSpeed":1.42,
            "windBearing":76,
            "visibility":9,
            "cloudCover":0.1,
            "pressure":1015.24,
            "ozone":242.3
         }
]

我可以每小时访问一次"和"数据"以下代码没有问题:

let hourly = json["hourly"] as? [String : Any],
let data = hourly["data"] as? [[String : Any]]

但我需要做的只是访问数据中的第一个Dictionary,我似乎无法弄明白。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您可以使用first这样的Array属性。

if let hourly = json["hourly"] as? [String : Any],
   let data = hourly["data"] as? [[String : Any]], 
   let firstDic = data.first {

     print(firstDic)
     //If you want `summary` value from firstDic
     print(firstDic["summary"])
}