在for循环中调用异步方法

时间:2018-01-14 20:55:31

标签: swift for-loop asynchronous grand-central-dispatch

当我在循环的每次迭代中进行异步调用时,尝试使我的for循环同步。我有一种感觉,我需要以某种方式使用Grand Central Dispatch,但不确定。

func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
    var results: [String] = []
    for string in strings {
        Service.shared.fetch(with: string, completion: { (result) in
            results.append(result)
        })
    }
    // this will run before asynchronous method in for-loop runs n times.
    completion(results)
}

1 个答案:

答案 0 :(得分:0)

您不需要使此循环同步。您真正想要的是在获得所有completion时致电results。您可以使用此解决方案(免费):

func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
    var results: [String] = []  

    for string in strings {
        Service.shared.fetch(with: string, completion: { (result) in
            DispatchQueue.main.async { 
                results.append(result)
                if results.count >= strings.count {
                    completion(results)
                }
            }
        )
    }
}