Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know when an iteration over array with async method is finished

Tags:

swift

Lets say i have an array of strings, and i call an async method that returns an int from it. I want to know when i have those int values in my array of ints.

let rndStrings = ["a", "b", "c"]
var rndInts = [Int]()
rndStrings.forEach { rndString in 
   someAsyncMethod { intResult in
     rndInts.append(intResult)
   }
}

I want to wait until rndInts has all 3 values

like image 830
Godfather Avatar asked Mar 01 '26 23:03

Godfather


1 Answers

Don't wait. Get notified with DispatchGroup.

let rndStrings = ["a", "b", "c"]
let group = DispatchGroup()
var rndInts = [Int]()
rndStrings.forEach { rndString in 
   group.enter()
   someAsyncMethod { intResult in
     rndInts.append(intResult)
     group.leave()
   }
}
group.notify(queue: DispatchQueue.main) {
   print("finished")
}
like image 68
vadian Avatar answered Mar 04 '26 14:03

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!