user1391152
user1391152

Reputation: 1289

Swift 3 accessing nested dictionaries within json feed

Hi I currently have a 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
         }
]

I can access "hourly" and "data" no problem with the following code:

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

But what I need to do is access the first Dictionary only within data, which I cannot seem to figure out. Can anybody help please?

Upvotes: 0

Views: 504

Answers (1)

Nirav D
Nirav D

Reputation: 72440

You can use first property of Array like this.

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"])
}

Upvotes: 1

Related Questions