简体   繁体   English

Swift中的完成处理程序

[英]Completion Handler in Swift

I have been searching for many hours trying to find the solution to this closure problem in swift. 我一直在寻找很多小时试图在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: 这是我试图转换为swift的Objective-C代码:

[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. directions是一个MKDirections对象。

Thanks! 谢谢!

Try 尝试

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

在此输入图像描述

This is the general way a block/closure looks like in Swift. 这是Swift中块/闭包的一般方式。

if you don't need to use the parameters you can do it like this 如果您不需要使用参数,您可以这样做

directions.calculateDirectionsWithCompletionHandler ({
(_) in 
  // your code here
    })

regarding the syntax of Closures in Swift , and checking the MKDirections Class Reference: 关于SwiftClosures的语法,以及检查MKDirections类参考:

在此输入图像描述

it looks the proper closure here should be an MKDirectionHandler , which defined as: 它看起来正确的闭包应该是一个MKDirectionHandler ,定义为:

在此输入图像描述

therefore the completion handler should look like this: 因此, 完成处理程序应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM