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

时间:2017-07-21 12:32:06

标签: ios json swift

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

说:

  

无法下标类型的值&#39; [字典]&#39;索引类型为字符串

我如何访问它?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

错误很明显。 steps [&#34; distance&#34;]是一个字典数组,可以像步骤[0],步骤[1]一样访问。 您需要更改以下行

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

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