What is a good example of closing a shelter in Swift?

I am reading a Swift programming language manual and mention closing. As for escaping closures, I don't know what they mean by "closing is passed as an argument to the function, but called after the function returns." Can someone provide an example about escaping closure?

+6
source share
2 answers

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 } // 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. 

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).

+2
source

In the closing options, Swift 3 defaults to unexposed.

We need to write the @escaping closure @escaping before the parameter type indicates that the closure is called after the function returns.

 typealias Operation = (Data?) -> () func addToQueue(data: Data?, operation: @escaping Operation) { OperationQueue.main.addOperation { operation(data) } } 

If we remove the @escaping attribute, Xcode will display an error message below

parameter error message without escaping

+2
source

All Articles