0
0
iOS Swiftmobile~5 mins

Task and TaskGroup in iOS Swift

Choose your learning style9 modes available
Introduction

Tasks let your app do work in the background without freezing the screen. TaskGroups help you run many tasks together and wait for all to finish.

When you want to download several images at the same time without stopping the app.
When you need to fetch data from multiple sources and combine the results.
When you want to perform several calculations in parallel to speed up your app.
When you want to run background work but still update the UI when done.
Syntax
iOS Swift
Task {
    // code to run asynchronously
}

await withTaskGroup(of: ReturnType.self) { group in
    group.addTask {
        // first async task
    }
    group.addTask {
        // second async task
    }
    for await result in group {
        // handle each result
    }
}

Use Task to start one asynchronous job.

Use withTaskGroup to run many tasks together and wait for all results.

Examples
This runs a simple task that prints a message without blocking the main thread.
iOS Swift
Task {
    print("Hello from a task!")
}
This runs two tasks in parallel that add numbers, then prints each result as they finish.
iOS Swift
await withTaskGroup(of: Int.self) { group in
    group.addTask { 1 + 1 }
    group.addTask { 2 + 2 }
    for await value in group {
        print("Result: \(value)")
    }
}
Sample App

This SwiftUI app has a button that starts three tasks in parallel. Each task does a simple math calculation. When all finish, the results show in a list.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var results: [Int] = []

    var body: some View {
        VStack(spacing: 20) {
            Button("Start Tasks") {
                Task {
                    await runTasks()
                }
            }
            List(results, id: \.self) { result in
                Text("Result: \(result)")
            }
        }
        .padding()
    }

    func runTasks() async {
        var tempResults: [Int] = []
        await withTaskGroup(of: Int.self) { group in
            group.addTask { 10 * 2 }
            group.addTask { 5 + 5 }
            group.addTask { 3 * 7 }

            for await value in group {
                tempResults.append(value)
            }
        }
        results = tempResults
    }
}
OutputSuccess
Important Notes

Tasks run asynchronously, so the app stays responsive.

withTaskGroup waits for all tasks to finish before continuing.

Use await to pause until a task or group finishes.

Summary

Task runs one background job.

withTaskGroup runs many jobs together and collects results.

Use these to keep your app smooth and fast.