Swift Closures in for loop
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")
})