我有JSON
我想访问距离中的所有步骤。
这是我的代码
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;索引类型为字符串
我如何访问它?
答案 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>