Trần Kim Dự February 2016

Swift: Explain grammar syntax for NSURLSession.sharedSession().dataTaskWithURL

I'm a new comer to iOS World. When I see a method for downloading file. I see this code:

        // create url
        let imageURL = NSURL(string: Constants.CatURL)!

        // create task
        let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) {
            (data, response, error) in print("task finished")
        }

I don't really understand part:

 {
        (data, response, error) in print("task finished")
    }

Where data response error objects come from? And which type are they? I'm familiar with some languages such Java, C# and above structure very strange: after a method call is a {} codeblock. I just see that in iOS there are two methods that very different from above:

let task = NSURLSession.sharedSession().dataTaskWithURL(url: NSURL)
let task = NSURLSession.sharedSession().dataTaskWithURL(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)

thanks :)

Answers


matt February 2016

The stuff in { ... } is an anonymous function body. The stuff in (...) in are the names of the parameters passed to the function.

The part of your question about "which type are they?" is a really good question. The answer is that Swift knows about this declaration, which you cited:

let task = NSURLSession.sharedSession().dataTaskWithURL(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)

So Swift already knows the types of the three parameters, and thus the types can optionally be omitted (and here they have in fact been omitted).

You may also be confused by the omission of the label completionHandler:. This is legal because this function is the last parameter. In that case, it is legal to drop the label and put the anonymous function body outside the function call parentheses (known as "trailing syntax").

Thus, the code you cited is in fact a legal form for implementing dataTaskWithURL(_:completionHandler:).

Post Status

Asked in February 2016
Viewed 2,821 times
Voted 9
Answered 1 times

Search




Leave an answer