Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completion Handler in Swift

I have been searching for many hours trying to find the solution to this closure problem in swift. I have found many resources for explaining the closures but for some reason I can't seem to get this working.

This is the Objective-C code I am trying to convert into swift:

[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
            NSLog(@"%@",[response description]);
            NSLog(@"%@",[error description]);

            }];

and the swift I am trying but is not working:

directions.calculateDirectionsWithCompletionHandler(response: MKDirectionsResponse?, error: NSError?) {
    println(response.description)
    println(error.description)
}

directions is an MKDirections object.

Thanks!

like image 817
Eytan Schulman Avatar asked Jul 03 '14 13:07

Eytan Schulman


People also ask

What is difference between closure and completion handler Swift?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable.

Is a completion handler a closure Swift?

A completion handler is nothing more than a regular closure that's called to indicate that some piece of work has completed or produced a result. The completion handler that you pass to the dataTask function (in this case via trailing closure syntax) is called once the data task completes.

What's the difference between Block and completion handler?

In short : Completion handlers are a way of implementing callback functionality using blocks or closures. Blocks and Closures are chunks of code that can be passed around to methods or functions as if they were values (in other words "anonymous functions" which we can give names to and pass around). Save this answer.

What is @escaping in Swift?

Wrapping Up. In Swift, closures are non-escaping by default. This means that the closure can't outlive the function it was passed into as a parameter. If you need to hold onto that closure after the function it was passed into returns, you'll need to mark the closure with the keyword @escaping.


1 Answers

Try

directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in 
        println(response?.description)
        println(error?.description)
    })
like image 194
Adithya Avatar answered Oct 07 '22 00:10

Adithya