ios - 什么时候在 swift 中使用闭包?

标签 ios swift closures

<分区>

我已经进行了几个月的 ios 开发,并且渴望在我的编程模式中实现新事物。

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

但我真的想知道除此之外它的用途。即我们应该在基本编程中的什么地方使用闭包。就像当我们想将信息从 child 发送给 parent 时我们使用委托(delegate)一样。那么任何可以在我们日常快速编程中使用的实际解释或简短示例都会有所帮助吗?

谁能告诉我这些闭包实际上是如何计算值的

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

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

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

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

我真的很想知道流量?

最佳答案

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

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

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 循环何时完成对非常大的数组的迭代。您将闭包 { println("work done") } 作为将在 for 循环完成其工作后执行的函数的输入参数,并打印“work done”。发生的事情是,你给 longAction 一个函数(闭包),并将其命名为 completion,当你在 longAction 中调用 completion 时,该函数将被执行。

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

let array = [1, 2, 3]
let smallerThanTwo = array.filter { $0 < 2 }

有了这个,你可以过滤掉小于 2 的数字。

已更新关于sorted(可能)的工作方式:

所以想法是,sorted 将遍历数组,并将两个连续元素 (i, i + 1) 相互比较,并在需要时交换它们。 “如果需要”是什么意思?您提供了闭包 { (s1: String, s2: String) -> Bool in return s1 > s2 },如果 s1,它将返回 true > 是 lexiographically大于 s2。如果闭包返回 truesorted 算法将交换这两个元素,并将其与接下来的两个元素(i + 1,i + 2,如果结束未达到数组)。所以基本上你必须为 sorted 提供一个闭包,它会告诉“何时”交换元素。

关于ios - 什么时候在 swift 中使用闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824488/

相关文章:

iOS Build 在 Xcode 中运行良好,但 Appcenter.ms 失败

swift - 更改屏幕尺寸时 Sprite 从场景中消失

ios - AVPlayerLayer 没有显示 AVPlayer 视频?

iphone - 如何解决/处理委派EXC_BAD_ACCESS错误?对象C

arrays - 根据 bool 值快速排序对象数组

rust - 如何从 `FnMut` 返回捕获的变量

javascript - 为什么这个函数记录未定义(JavaScript 闭包)

javascript - 闭包和柯里化(Currying)中的引用如何在 js 中工作?

ios - 不兼容的指针类型将 'Class' 发送到类型为 'id<UIActionSheetDelegate>' 的参数

xcode - 带有超链接的 Swift 2 TableView 单元格