繁体   English   中英

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

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

我有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

我想访问距离中所有的值,这是逐步的。

这是我的代码

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()

}

我在以下方面遇到错误:

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

其中说:

无法用字符串类型的索引下标“ [字典]”类型的值

我该如何访问?

您正在尝试通过键访问字典数组的值。 您应该将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)
    }
}

错误很明显。 steps [“ distance”]是字典的数组,可以像step [0],steps [1]一样访问。 您需要更改以下行

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

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

暂无
暂无

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

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