vasu
vasu

Reputation: 25

How to iterate array of dictionaries having nested dictionary?

I have JSON

http://maps.googleapis.com/maps/api/directions/json?&origin=28.594517,77.049112&destination=28.654109,77.34395&travelMode=DRIVING&provideRouteAlternatives=false&sensor=false

I want to access all the values in distance which is in steps.

Here is my code

class Router {
var getValue = Double()

func downloadData(complete: downloadComplete) {

    let currentURL = URL(string:getURL)!
    Alamofire.request(currentURL).responseJSON { (responseJSON) in
        let result = responseJSON
        //            print(result)

        if let dict = result.value as? Dictionary<String,AnyObject>{

            if let routes = dict["routes"] as? [Dictionary<String, AnyObject>]{

                if let legs = routes[0]["legs"] as? [Dictionary<String, AnyObject>]{

                    if let steps = legs[0]["steps"] as? [Dictionary<String, AnyObject>]{

                        for index in steps{
                            if let distance = steps["distance"] as? Dictionary<String,AnyObject>{
                                if let value = distance["value"] as? Double{
                                    self.getValue = self.getValue + value
                                    print(self.getValue)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    complete()

}

I am getting error in:

if let distance = steps["distance"] as? Dictionary<String,AnyObject>{

which says:

Cannot subscript a value of type '[Dictionary]' with an index of type string

How can I access this?

Upvotes: 1

Views: 496

Answers (2)

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

The error is clear. steps["distance"] is an array of dictionaries, which can be accessed like steps[0],steps[1]. You need to change following line

if let distance = steps["distance"] as? Dictionary<String,AnyObject>

to

if let distance = index["distance"] as? Dictionary<String,AnyObject>

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54745

You are trying to access the value of an array of dictionaries by key. You should change steps["distance"] to index["distance"].

if let distance = index["distance"] as? Dictionary<String,AnyObject>{
    if let value = distance["value"] as? Double{
        self.getValue = self.getValue + value
        print(self.getValue)
    }
}

Upvotes: 2

Related Questions