An example of closing shielding can be a completion handler in some asynchronous task, for example, initiating a network request:
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() }
And it is called like this:
performRequest(["foo" : "bar"]) { data, error in guard error == nil else { print(error) return }
This completionHandler closure is considered escaping because the NSURLSession dataTaskWithRequest method executes asynchronously (i.e., it returns immediately, and its own closure will be called later when the request completes).
source share