Reputation: 25
I have JSON
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?
Upvotes: 1
Views: 496
Reputation: 5241
The error is clear. steps["distance"] is an array of dictionaries, which can be accessed like steps[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>
Upvotes: 0
Reputation: 54745
You are trying to access the value of an array of dictionaries by key. You should change steps["distance"]
to 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)
}
}
Upvotes: 2