我正在阅读Swift编程语言手册,它提到了逃避关闭。关于转义闭包,我不知道它们是什么意思"闭包作为参数传递给函数,但在函数返回后调用。"有人可以提供一个关于转义闭包的例子吗?
答案 0 :(得分:2)
转义闭包的一个例子是某些异步任务中的完成处理程序,例如启动网络请求:
func performRequest(parameters: [String: String], completionHandler: (NSData?, NSError?) -> ()) {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
completionHandler(data, error)
}
task.resume()
}
这就是这样称呼的:
performRequest(["foo" : "bar"]) { data, error in
guard error == nil else {
print(error)
return
}
// now use data here
}
// Note: The `completionHandler` above runs asynchronously, so we
// get here before the closure is called, so don't try to do anything
// here with `data` or `error`. Any processing of those two variables
// must be put _inside_ the closure above.
这个completionHandler
闭包被认为是转义,因为NSURLSession
方法dataTaskWithRequest
异步运行(即它立即返回,并且在请求完成后稍后将调用它自己的闭包)。
答案 1 :(得分:2)