[英]How to iterate array of dictionaries having nested dictionary?
我有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>{
其中說:
無法用字符串類型的索引下標“ [字典]”類型的值
我該如何訪問?
您正在嘗試通過鍵訪問字典數組的值。 您應該將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.