Completion Handler in Swift
11,191
Solution 1
Try
directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in
println(response?.description)
println(error?.description)
})
Solution 2
This is the general way a block/closure looks like in Swift.
if you don't need to use the parameters you can do it like this
directions.calculateDirectionsWithCompletionHandler ({
(_) in
// your code here
})
Solution 3
regarding the syntax of Closures in Swift, and checking the MKDirections
Class Reference:
it looks the proper closure here should be an MKDirectionHandler
, which defined as:
therefore the completion handler should look like this:
direction.calculateDirectionsWithCompletionHandler( { (response: MKDirectionsResponse!, error: NSError!) -> () in
println(response.description)
println(error.description)
} )
Comments
-
Eytan Schulman almost 2 years
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!