简体   繁体   English

如何迭代具有嵌套字典的字典数组?

[英]How to iterate array of dictionaries having nested dictionary?

I have JSON 我有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 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? 我该如何访问?

You are trying to access the value of an array of dictionaries by key. 您正在尝试通过键访问字典数组的值。 You should change steps["distance"] to index["distance"] . 您应该将steps["distance"]更改为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)
    }
}

The error is clear. 错误很明显。 steps["distance"] is an array of dictionaries, which can be accessed like steps[0],steps[1]. steps [“ distance”]是字典的数组,可以像step [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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM