iOS and macOS apps often need to perform tasks multiple times. To help achieve great performance, apps can perform repeated work in parallel. Swift's implementation of Grand Central Dispatch, also known as Dispatch and GCD, provides two great options for implementing parallel execution of for loop iterations:

  1. Regular Swift For Loops
  2. Parallel For Loops using DispatchQueue
  3. Parallel For Loops using DispatchGroup

Regular Swift For Loops

A regular for loop iterates over a specified range with serial execution, meaning each iteration is performed one after the other:

// Perform expensiveWork in sequence for each task
// in a list of tasks
for task in tasks {
    expensiveWork(task: task)
}

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(task: tasks[index])
}

Parallel For Loops using DispatchGroup

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

// 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 from GCD you can implement high-performance parallel processing for loops in Swift.