Swift completion handler

I searched for many hours trying to find a solution to this closure problem in swift. I found a lot of resources to explain the closure, but for some reason I cannot get this to work.

This is the Objective-C code I'm trying to convert to fast:

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

and quick, I'm trying but not working:

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

is an MKDirections object.

Thanks!

+7
ios swift mapkit mkmapview routes swift-converter
source share
3 answers

Try

 directions.calculateDirectionsWithCompletionHandler ({ (response: MKDirectionsResponse?, error: NSError?) in println(response?.description) println(error?.description) }) 
+10
source share

enter image description here

This is the general way lock / close looks in Swift.

if you do not need to use parameters you can do this:

 directions.calculateDirectionsWithCompletionHandler ({ (_) in // your code here }) 
+2
source share

regarding Swift's Closures syntax and MKDirections validation MKDirections reference:

enter image description here

it looks right, here should be MKDirectionHandler , which is defined as:

enter image description here

therefore, the completion handler should look like this:

 direction.calculateDirectionsWithCompletionHandler( { (response: MKDirectionsResponse!, error: NSError!) -> () in println(response.description) println(error.description) } ) 
+1
source share

All Articles