什么时候使用闭包在swift? [英] When to use closures in swift?

查看:141
本文介绍了什么时候使用闭包在swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在ios开发几个月,渴望在我的编程模式中实现新的东西。



现在我正在学习闭包,知道一些关于它的语法,知道它可以使用代替委托回调。除了在一些UIViewAnimation中实现它和排序。



但真的我想知道它的用途除了that.i.e我们应该在我们的基本编程中使用闭包。就像我们使用委托,当我们想要发送信息从孩子到父母..所以任何解释或简单的例子,其实际上可以用于我们的日常swift编程将是有帮助的?



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

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

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



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

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



我真的想知道流程?

解决方案

两个最常用的例子是Swift中的完成块和高阶函数。



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

  func longAction(completion: ;()){
用于veryLargeArray中的索引{
//使用veryLargeArray执行某些操作,这是非常耗时的
}
completion()//通知调用者longAction完成
}

//或asynch版本
func longAction(completion:() - >()){

dispatch_async(dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT,0)){

用于veryLargeArray中的elem {
//使用veryLargeArray执行某些操作,这是非常耗时的
}
dispatch_async(dispatch_get_main_queue ),{
completion()//通知调用者longAction已完成
})
}
}

longAction {print done)}



在上面的例子中,当你有一个耗时的任务,你想知道当for循环完成遍历非常大的数组时。你把闭包 {println(work done)} 作为将在for循环完成其工作之后执行的函数的输入参数,并打印work done 。发生了什么事情,你给一个函数(闭包)到longAction并将其命名为 completion ,并且当你调用 completion

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

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

这样,您可以筛选出小于2的数字。



UPDATED 关于如何排序(可能)工作原理:



所以这个想法是,排序将遍历数组,并且比较两个连续的元素(i,i + 1)彼此,并且如果需要交换它们。 如果需要是什么意思?您提供了 {(s1:String,s2:String) - > Bool返回s1>如果 s1 ,则会返回 true //en.wikipedia.org/wiki/Lexicographical_orderrel =nofollow>词性大于 s2 。如果该闭包返回 true ,则 sorted 算法将交换这两个元素,并计算下两个元素(i + 1,i + 2,如果未到达阵列的末端)。所以基本上你必须为 sorted 提供一个闭包,它会告诉when换成元素。


I am been to ios development for few months and eager to implement new things in my programming pattern.

Now i am learning closures and knew little things about its syntax,knew it can be used instead of delegate for callbacks. As well as implemented it in some UIViewAnimation and for sorting.

But really i want to know its uses apart from that.i.e where should we use closures in our basic programming. Like we use delegate when we want to send information from child to parent.. So any explanation or brief example on its actual which can be used in our day to day swift programming would be helpful?

Can anyone tell me how these closure actually computes the value

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

In these example there is names and closure as an argument to a method..but how does this actually computes ?

Can you please explain how these works when passing closures in this animation code :

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

I really want to know about the flow?

解决方案

The two most used cases are completion blocks and higher order functions in Swift.

Completion blocks: for example, when you have some time consuming task, you want to be notified when that task is finished. You can use closures for that, instead of a delegate (or many other things)

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") }

In the example above, when you have a time consuming task, you want to know when the for loop finishes iterating through the very large array. You put the closure { println("work done") } as an input parameter for the function which will be executed after the for loop finishes its work, and print "work done". And what happened is that you gave a function (closure) to longAction and name it to completion, and that function will be executed when you call completion in longAction.

Higher order functions: you can use closures as input parameters for higher order functions, for example:

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

With this, you can filter out the numbers that are smaller than 2.

UPDATED About how sorted (probably) works:

So the idea is, that sorted will go through the array, and compare two consecutive elements (i, i + 1) with each other, and swap them, if needed. What does it mean "if needed"? You provided the closure { (s1: String, s2: String) -> Bool in return s1 > s2 }, which will return true if s1 is lexiographically greater than s2. And if that closure returned true, the sorted algorithm will swap those two elements, and countinues this with the next two elements (i + 1, i + 2, if the end of the array is not reached). So basically you have to provide a closure for sorted which will tell "when" to swap to elements.

这篇关于什么时候使用闭包在swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆