【问题标题】:Completion Handler in SwiftSwift 中的完成处理程序
【发布时间】:2014-07-03 13:25:00
【问题描述】:

我已经搜索了好几个小时,试图快速找到解决这个关闭问题的方法。我找到了很多解释关闭的资源,但由于某种原因,我似乎无法让它发挥作用。

这是我试图转换成 swift 的 Objective-C 代码:

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

            }];

我正在尝试但不工作的 swift:

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

directions 是一个MKDirections 对象。

谢谢!

【问题讨论】:

    标签: ios mkmapview swift mapkit routes


    【解决方案1】:

    试试

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

    【讨论】:

    • 这工作非常感谢!上帝..闭包.. XD 我会在允许的时候标记为答案。再次感谢!
    • 或简称:directions.calculateDirectionsWithCompletionHandler ({(response, error) in /* code */ })
    【解决方案2】:

    这是 Swift 中块/闭包的一般方式。

    如果你不需要使用参数,你可以这样做

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

    【讨论】:

      【解决方案3】:

      关于 SwiftClosures 的语法,并检查MKDirections 类参考:

      看起来这里正确的闭包应该是MKDirectionHandler,其定义为:

      因此,完成处理程序应该如下所示:

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

      【讨论】:

      • 这篇文章被标记为低质量。尽管您享有盛誉,请添加更多解释。
      • @Jean-RémyRevy,我的错,对不起。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多