我在ios开发工作了几个月,并渴望在我的编程模式中实现新的东西.
现在我正在学习闭包并且对它的语法知之甚少,知道它可以用来代替回调委托.以及在一些UIViewAnimation和排序中实现它.
但我真的想知道它的用途除了那个.我们应该在基本编程中使用闭包.就像我们想要将信息从孩子发送到父母那样我们使用委托.所以任何关于它的实际的解释或简短例子可以用在我们日常的快速编程中会有帮助吗?
任何人都可以告诉我这些闭包实际上如何计算价值
reversed = sorted(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )
Run Code Online (Sandbox Code Playgroud)
在这些示例中,名称和闭包作为方法的参数.但这实际上是如何计算的?
在这个动画代码中传递闭包时,能否解释一下这些是如何工作的:
UIView.animateWithDuration(duration: NSTimeInterval,
animations: (() -> Void)?,
completion: ((Bool) -> Void)?)
Run Code Online (Sandbox Code Playgroud)
我真的想知道流量吗?
Dán*_*agy 21
最常用的两种情况是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") }
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,当您有一个耗时的任务时,您想知道for循环何时完成迭代非常大的数组.您将闭包{ println("work done") }作为函数的输入参数,该函数将在for循环完成其工作后执行,并打印"work done".发生的事情是你给longAction一个函数(闭包)并将其命名为completion,并且当你调用completionlongAction 时将执行该函数.
高阶函数: 您可以使用闭包作为高阶函数的输入参数,例如:
let array = [1, 2, 3]
let smallerThanTwo = array.filter { $0 < 2 }
Run Code Online (Sandbox Code Playgroud)
这样,您可以过滤掉小于2的数字.
更新关于sorted(可能)如何工作:
所以我的想法是,排序将通过数组,并将两个连续的元素(i,i + 1)相互比较,并在需要时交换它们.什么意思"如果需要"?你提供了闭包{ (s1: String, s2: String) -> Bool in return s1 > s2 },true如果s1在词汇表上大于,则会返回s2.如果该闭包返回true,sorted算法将交换这两个元素,并使用接下来的两个元素(i + 1,i + 2,如果未到达数组的末尾)对此进行计数.所以基本上你必须提供一个闭包sorted,它将告诉"何时"交换元素.
| 归档时间: |
|
| 查看次数: |
9310 次 |
| 最近记录: |