Sonic Master
Sonic Master

Reputation: 1248

Get value from dictionary as an array in Swift 2

I am relatively new to swift and I have a little problem here. I have a JSON already serialized as a dictionary. This is how I get the dictionary

guard let result = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String:AnyObject] else {
                    print("Error trying to convert data to JSON")
                    completionHandler(nil, response, error)
                    return
                }

Here is my dictionary

{
  "count": "68",
  "earthquakes": [
    {
      "src": "us",
      "eqid": "b000gbf8",
      "timedate": "2013-04-19 03:05:53",
      "lat": "46.1817",
      "lon": "150.7960",
      "magnitude": "7.2",
      "depth": "122.30",
      "region": "Kuril Islands"
    },
    {
      "src": "us",
      "eqid": "b000g7x7",
      "timedate": "2013-04-16 10:44:20",
      "lat": "28.1069",
      "lon": "62.0532",
      "magnitude": "7.8",
      "depth": "82.00",
      "region": "Iran-Pakistan border region"
    }
  ]
}

I want to get those earthquakes as an array that I could iterate every item in it.

I try to create a temp var for that

let eqs = resultJSON["earthquakes"]

But, I can't iterate through eqs. My point is, I want to make an array that comes from that dictionary.

How is that possible? Any help would be appreciated. Thank you.

Upvotes: 1

Views: 2138

Answers (1)

vadian
vadian

Reputation: 285039

The key earthquakes contains the array which has String keys and values

if let earthquakes = result["earthquakes"] as? [[String:String]] {
    for earthquake in earthquakes {
        let lat = earthquake["lat"]!
        let lon = earthquake["lon"]!
        // get other values
        print(lat, lon)
    }
}

Upvotes: 3

Related Questions