DevPrep

All topics › Real interview tasks

Find the bug in this DispatchGroup code

Middle PRO

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store