本文介绍了知道使用异步方法对数组的迭代何时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个字符串数组,我调用了一个从它返回一个 int 的异步方法.我想知道我的 int 数组中何时有这些 int 值.
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)
}
}
我想等到 rndInts 拥有所有 3 个值
I want to wait until rndInts has all 3 values
推荐答案
不要等待.通过 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")
}
这篇关于知道使用异步方法对数组的迭代何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!