解决方法
转义闭包的一个示例是某些异步任务中的完成处理程序,例如启动网络请求:
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是异步运行的(即它立即返回,并且在请求完成后稍后将调用它自己的闭包).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。