Swift 中最常用的两种情况是完成块和高阶函数。
完成块:例如,当您有一些耗时的任务时,您希望在该任务完成时收到通知。您可以为此使用闭包,而不是委托(或许多其他东西)
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 循环完成其工作后执行,并打印“工作完成”。而发生的事情是你给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 是lexiographically 大于s2,它将返回true。如果该闭包返回true,sorted 算法将交换这两个元素,并将其与接下来的两个元素(i + 1,i + 2,如果未到达数组末尾)进行计数。所以基本上你必须为sorted 提供一个闭包,它会告诉“何时”交换元素。