calling asynchronous method inside for-loop [duplicate]

ε祈祈猫儿з 提交于 2019-12-06 16:29:27

You don't need to make this loop synchronous. What you really want is to call completion when you will get all results. You can use this solution (for free):

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)
                }
            }
        )
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!