我的另一个问题被标记为与另一个问题相同,但它没有回答我遇到的问题。
以下是代码:
if status == "OK" {
self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0]
self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>
let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>>
let steps = legs[0]["steps"]!
for i in 0...steps.count - 1 {
let step_coordinate = steps[i]["start_location"]!
print(step_coordinate!["lat"]!!)
}
}
print语句给出了这个结果
40.7609205
40.7640121
40.7595325
40.7501637
40.7481923
40.7393448
40.7252038
40.7225337
40.718295
但如果我将print语句交换为抓取值并将它们放入数组中,我会收到致命错误:找到nil。
有人可以解释为什么会这样吗?如果没有通过for循环,我如何获取这些值?
答案 0 :(得分:1)
这是您的代码的更简洁版本。
规则:
[NSObject: AnyObject]
次查找的值。guard
语句和if let
安全地展开选项。if status == "OK" {
guard let routes = dictionary["routes"] as? [[NSObject: AnyObject]] else { return }
self.selectedRoute = routes.first ?? [:]
self.overviewPolyline = self.selectedRoute["overview_polyline"] as? [NSObject: AnyObject] ?? [:]
guard let legs = self.selectedRoute["legs"] as? [[NSObject: AnyObject]] else { return }
let firstleg = legs.first ?? [:]
guard let steps = firstleg["steps"] as? [[NSObject: AnyObject]] else { return }
for step in steps {
if let step_coordinate = step["start_location"] as? [NSObject: AnyObject] {
if let lat = step_coordinate["lat"] as? Double {
print(lat)
// append lat to array of lats
lats.append(lat)
}
}
}
}