2

This code is used to answer the question here:

How to make an HTTP request in Swift?

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

The docs for dataTaskWithURL say the following:

func dataTaskWithURL(_ url: NSURL,
   completionHandler completionHandler: ((NSData!,
                              NSURLResponse!,
                              NSError!) -> Void)?) -> NSURLSessionDataTask

So it appears the {(data .... } portion of the first code block is the completion handler. I come from a Java background where this would be expressed like so:

dataTaskWithUrl(url, function(data, ....) { .... });

Could someone explain why the completion handler is not the second argument in the method call?

Community
  • 1
  • 1
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105

1 Answers1

2

It's a Trailing Closure:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports

Mike S
  • 41,895
  • 11
  • 89
  • 84