2014-07-03 81 views
7

我一直在寻找很多小时试图在swift中找到解决此问题的解决方案。我发现了很多解释闭包的资源,但由于某种原因,我似乎无法得到这个工作。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) 
} 

方向是MKDirections对象。

谢谢!

回答

10

尝试

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

这个工作非常感谢!上帝..闭包.. XD我会标记为答案,当它让我。再次感谢! –

+0

太棒了!没问题。 – Adithya

+0

或简称:'directions.calculateDirectionsWithCompletionHandler({(response,error)in/* code * /})' – David

1

关于Closures斯威夫特语法,并检查MKDirections类参考:

enter image description here

它看起来正确关闭这里应该是一个MKDirectionHandler,这定义为:

enter image description here

因此完成处理应该是这样的:

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

这篇文章被标记为低质量。尽管你的名誉,请添加更多的解释。 –

+0

@ Jean-RémyRevy,我的坏,对不起。 – holex

+0

没问题:)。现在好了:)! –

2

enter image description here

这是一般的方式块/关闭看起来像雨燕。

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

directions.calculateDirectionsWithCompletionHandler ({ 
(_) in 
    // your code here 
    }) 
相关问题