0
0
Swiftprogramming~5 mins

Task groups for parallel execution in Swift

Choose your learning style9 modes available
Introduction

Task groups help run many tasks at the same time easily. This makes programs faster by doing work in parallel.

When you want to download many images from the internet at once.
When you need to process multiple files at the same time.
When you want to run several calculations simultaneously to save time.
When you want to fetch data from different sources in parallel.
When you want to perform many small tasks without waiting for each to finish.
Syntax
Swift
await withTaskGroup(of: ReturnType.self) { group in
    group.addTask {
        // code for one task
        return result
    }
    // add more tasks
    for await result in group {
        // handle each result
    }
}

Use await because tasks run asynchronously.

Each task returns a value of the specified type.

Examples
This runs two tasks that add numbers and prints their results as they finish.
Swift
await withTaskGroup(of: Int.self) { group in
    group.addTask { 1 + 1 }
    group.addTask { 2 + 2 }
    for await result in group {
        print(result)
    }
}
This creates three tasks that return messages and prints each message.
Swift
await withTaskGroup(of: String.self) { group in
    for i in 1...3 {
        group.addTask { "Task \(i) done" }
    }
    for await message in group {
        print(message)
    }
}
Sample Program

This program runs five tasks in parallel. Each task waits a bit and then returns the square of a number. The results print as they finish.

Swift
import Foundation

@main
struct Main {
    static func main() async {
        await withTaskGroup(of: Int.self) { group in
            for i in 1...5 {
                group.addTask {
                    // Simulate work with sleep
                    try? await Task.sleep(nanoseconds: UInt64(i) * 100_000_000)
                    return i * i
                }
            }
            for await square in group {
                print("Square: \(square)")
            }
        }
    }
}
OutputSuccess
Important Notes

Task groups run tasks concurrently, but order of results may vary.

Use for await to get results as tasks complete.

Task groups help manage many tasks without complex code.

Summary

Task groups let you run many tasks at the same time easily.

Use addTask to add work inside the group.

Collect results with for await to handle each task's output.