So, I'm having a bit of a time trying to get DispatchGroup to keep a for loop from iterating before a long asynchronous operation has completed. Most examples I've found are fairly straight forward and clear, but I can't seem to get my simple test case to work as I would expect.
let group = DispatchGroup()
for i in 1...3 {
group.enter()
print("INDEX \(i)")
asynchronousOperation(index: i, completion: {
print("HELLO \(i)")
self.group.leave()
})
print("OUTSIDE \(i)")
}
func asynchronousOperation(index: Int, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+5) {
print("DONE \(index)")
completion()
}
}
This ends up printing
START
INDEX 1
OUTSIDE 1
INDEX 2
OUTSIDE 2
INDEX 3
OUTSIDE 3
DONE 1
HELLO 1
DONE 2
HELLO 2
DONE 3
HELLO 3
I would've expected it to print something more like
START
INDEX 1
OUTSIDE 1
HELLO 1
INDEX 2
OUTSIDE 2
HELLO 2
INDEX 3
OUTSIDE 3
HELLO 3
Insofar as the next "INDEX" following an OUTSIDE wouldn't be printed until group.leave() had been called inside the asynchronousOperation()
Probably something simple I'm misunderstanding — any ideas?