Parallel For Loops in Swift

Implementing apps with great performance is important. Swift contains two great options for implementing parallel processing in loops:

  1. Parallel For Loops using DispatchQueue
  2. Parallel For Loops using DispatchGroup

Parallel For Loops using DispatchQueue

One way to parallelize work in Swift is to use DispatchQueue.concurrentPerform(iterations:, execute:). For a given number of iterations, DispatchQueue.concurrentPerform will perform the execute block in parallel:

// Perform expensiveWork in parallel for each task
// in a list of tasks
DispatchQueue.concurrentPerform(iterations: tasks.count) { (index) in
    expensiveWork(index: tasks[index])
}

Parallel For Loops using DispatchGroup

To perform parallel operations in an asynchronous manner, use a DispatchGroup. DispatchGroup has a notify(queue:, execute:) interface that will call the completion block execute on the specified queue when all DispatchGroup tasks complete:

// Create a dispatch group
let group = DispatchGroup()

// Perform expensiveWork in parallel for each task
// in a list of tasks
for task in tasks {
    // group.enter() is used to denote the start
    // of an expensive task
    group.enter()

    expensiveWork(task: task) { (_) in
        // Mark this task as complete with group.leave()
        group.leave()
    }
}

// Use group.notify to receive a callback when all of
// the dispatch group tasks have finished
group.notify(queue: .main) {
    // Handle completion
}

Parallel Processing in Swift

That’s it! By using DispatchQueue and DispatchGroup you can implement high performance parallel processing in Swift.