我正在努力理解Swift闭包,特别是如何从中获取数据。以下代码生成http get请求并从URL检索数据。一切正常。我可以在闭包内打印出这些数据,但无法确定如何存储到外部变量或返回数据。代码完成时, routes 变量为nil。有谁知道我做错了什么和/或如何从闭包中获取数据。
var routes: [String]?
let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error")
return
} //end let
do {
if let jsonDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
if let response = jsonDict.value(forKey: "response") as? NSArray {
for i in 0..<response.count {
let route = response.object(at: i) as! NSDictionary
print(route.value(forKey: "route_id")!)
routes?.append(route.value(forKey: "route_id")! as! String)
}
self.routes = routes
print(self.routes)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
task.resume()
输出:
11201-20180605110613_v67.1
11202-20180524131340_v66.89
11201-20180524131340_v66.89
11202-20180605110613_v67.1
nil