何时在swift中使用闭包?

时间:2015-04-23 13:11:14

标签: ios swift closures

我已经在ios开发中工作了几个月,并且渴望在我的编程模式中实现新的东西。

现在我正在学习闭包并且对它的语法知之甚少,知道它可以用来代替回调委托。以及在一些UIViewAnimation和排序中实现它。

但实际上我想了解它的用途。我们应该在基本编程中使用闭包。就像我们在想要将信息从孩子发送到父母时使用委托一样。所以关于其实际的任何解释或简短的例子可以在我们的日常快速编程中使用会有帮助吗?

任何人都可以告诉我这些闭包实际上如何计算值

reversed = sorted(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )

在这些示例中,有一个名称和闭包作为方法的参数。但是这实际上是如何计算的?

在这个动画代码中传递闭包时,请解释一下这些是如何工作的:

UIView.animateWithDuration(duration: NSTimeInterval, 
    animations: (() -> Void)?, 
    completion: ((Bool) -> Void)?)

我真的想知道这个流程吗?

3 个答案:

答案 0 :(得分:17)

最常用的两种情况是Swift中的完成块和高阶函数。

完成块:例如,当您有一些耗时的任务时,您希望在该任务完成时收到通知。您可以使用闭包,而不是委托(或许多其他东西)

@RequestParam

在上面的示例中,当您有一个耗时的任务时,您想知道for循环何时完成迭代非常大的数组。您将闭包func longAction(completion: () -> ()) { for index in veryLargeArray { // do something with veryLargeArray, which is extremely time-consuming } completion() // notify the caller that the longAction is finished } //Or asynch version func longAction(completion: () -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { for elem in veryLargeArray { // do something with veryLargeArray, which is extremely time-consuming } dispatch_async(dispatch_get_main_queue(), { completion() // notify the caller that the longAction is finished }) } } longAction { print("work done") } 作为函数的输入参数,该函数将在for循环完成其工作后执行,并打印" work done"。发生的事情是你给longAction一个函数(闭包)并将它命名为{ println("work done") },当你在longAction中调用completion时,该函数将被执行。

高阶函数:您可以使用闭包作为高阶函数的输入参数,例如:

completion

使用此功能,您可以过滤掉小于2的数字。

更新关于let array = [1, 2, 3] let smallerThanTwo = array.filter { $0 < 2 } (可能)如何运作:

所以我的想法是,sort会遍历数组,并将两个连续的元素(i,i + 1)相互比较,并在需要时交换它们。这是什么意思&#34;如果需要&#34;?您提供了关联sorted,如果{ (s1: String, s2: String) -> Bool in return s1 > s2 } lexiographically大于true,则会返回s1。如果该闭包返回s2,则true算法将交换这两个元素,并使用接下来的两个元素(i + 1,i + 2,如果未到达数组的末尾)对此进行计数)。所以基本上你必须为sorted提供一个关闭,它将告诉&#34;何时&#34;交换元素。

答案 1 :(得分:1)

  1. 通常,与其他功能相比,Closures没有名称。这意味着当你想要将代码块传递给某个函数而不将该代码包装到命名方法中时,它们可以在每种情况下使用。排序是最受欢迎的例子。

  2. 闭包可以使用其边界之外的变量。所谓的“捕获价值”

答案 2 :(得分:0)

闭包就像:

{ (params) -> returnType in
  statements
}

以下是从Apple doc

中使用它的原因
  
      
  • 从上下文中推断参数和返回值类型
  •   
  • 单表达式闭包的隐式返回
  •   
  • 速记参数名称
  •   
  • 尾随关闭语法
  •