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!
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.
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.
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.
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.
Try
directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in
println(response?.description)
println(error?.description)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With