Find the bug in this DispatchGroup code
Task
The function must run work for all items in parallel, collect the results in the original order and call completion once. Where's the bug?
func performAll<T>(_ items: [T],
work: @escaping (T, @escaping (T) -> Void) -> Void,
completion: @escaping ([T]) -> Void) {
let group = DispatchGroup()
let queue = DispatchQueue(label: "perform", attributes: .concurrent)
var result = items
group.notify(queue: .main) {
completion(result)
}
for (index, item) in items.enumerated() {
queue.async {
group.enter()
work(item) { response in
queue.async(flags: .barrier) {
result[index] = response
group.leave()
}
}
}
}
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep