for 循环中的 Swift 闭包 [英] Swift Closures in for loop

查看:35
本文介绍了for 循环中的 Swift 闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有在循环内执行闭包的代码.我想知道所有闭包何时完成执行.目前我正在使用一个计数器并在关闭完成时增加它,然后将它与要执行的次数进行比较.代码如下

Currently I am having code which executes a closure inside a loop. I want to know when all the closures have finished executing. Currently I am using a counter and incrementing it when the closure is completed and then I compare it with the no of times to be executed. Code is below

var count = 0
var noOfTimes = 10
for i in 0..<noOfTimes {
    someVariable.someClosure {
        result in
        count = count + 1
        if count == noOfTimes {
            //do something
        }
    }
}

在没有计数器的情况下,有没有更好的方法来做到这一点.谢谢.

Is there a better way to do this without the counter. Thanks.

推荐答案

您可以为此使用 DispatchGroup.它就像一个计数信号量.您可以通过调用enter 增加计数,通过调用leave 减少计数.您可以使用 notify 来安排在计数达到 0 时执行的闭包:

You can use a DispatchGroup for this. It works like a counted semaphore. You can increase the count by calling enter and decrease the count by calling leave. You can schedule a closure to be executed when the count reaches 0 using notify:

let dispatchGroup = DispatchGroup()
var noOfTimes = 10
for i in 0..<noOfTimes {
    dispatchGroup.enter()  //  Enter the dispatch group
    someVariable.someClosure {
        result in
        // Process result
        ...
        dispatchGroup.leave() // Exit dispatch group
    }
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
    print("All Done")
})

这篇关于for 循环中的 Swift 闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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