Bird
Raised Fist0
Swiftprogramming~10 mins

Task groups for parallel execution in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Task groups for parallel execution
Start Task Group
↓
Add Tasks to Group
↓
Run Tasks in Parallel
↓
Wait for All Tasks to Finish
↓
Collect Results
↓
End Task Group
This flow shows how tasks are added to a group, run at the same time, and then results are collected after all finish.
Execution Sample
Swift
func fetchData() async {
  await withTaskGroup(of: Int.self) { group in
    group.addTask { await fetchNumber(1) }
    group.addTask { await fetchNumber(2) }

    var sum = 0
    for await number in group {
      sum += number
    }
    print("Sum: \(sum)")
  }
}
This code runs two tasks in parallel that fetch numbers, then sums and prints the result.
Execution Table
StepActionTask Group StateTask ResultOutput
1Start task groupEmpty group--
2Add task 1 (fetchNumber(1))Group with 1 task--
3Add task 2 (fetchNumber(2))Group with 2 tasks--
4Run tasks in parallelRunning 2 tasks--
5Task 1 completes1 task done, 1 running1-
6Task 2 completesAll tasks done2-
7Sum results (1 + 2)All tasks done-Sum: 3
8End task groupGroup closed--
💡 All tasks finished and results summed, task group ends.
Variable Tracker
VariableStartAfter Step 5After Step 6After Step 7Final
sum01333
group stateempty1 task doneall doneall doneclosed
Key Moments - 3 Insights
Why do tasks run at the same time instead of one after another?
Because tasks are added to a task group which runs them concurrently, as shown in steps 4 to 6 in the execution table.
How does the program know when all tasks are finished?
The for-await loop waits for each task result until all tasks complete, indicated by step 6 where all tasks are done.
Why is the sum variable updated inside the for-await loop?
Because each task result arrives asynchronously, the loop adds each number as it comes, shown in steps 5 and 6 updating sum.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'sum' after step 5?
A0
B1
C2
D3
💡 Hint
Check the variable_tracker row for 'sum' after step 5.
At which step does the task group have all tasks done?
AStep 4
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the 'Task Group State' column in the execution_table.
If we add a third task returning 3, what would be the final sum after step 7?
A6
B5
C3
D4
💡 Hint
Sum is the total of all task results; adding 1 + 2 + 3 = 6.
Concept Snapshot
Task groups let you run many tasks at once.
Add tasks to the group with addTask.
Tasks run in parallel.
Use for-await to get results as they finish.
Waits until all tasks complete before continuing.
Full Transcript
This visual trace shows how Swift's task groups work for parallel execution. First, a task group starts empty. Then tasks are added to it. The group runs all tasks at the same time. As each task finishes, its result is collected. The sum variable adds each result inside a for-await loop. When all tasks finish, the final sum is printed. The task group then ends. This method helps run multiple jobs simultaneously and wait for all to complete before moving on.

Practice

(1/5)
1. What is the main purpose of using a TaskGroup in Swift concurrency?
easy
A. To run multiple tasks in parallel and wait for all to complete
B. To create a single long-running task
C. To pause the current task indefinitely
D. To handle errors in synchronous code

Solution

  1. Step 1: Understand what TaskGroup does

    A TaskGroup lets you run many tasks at the same time, managing them together.
  2. Step 2: Identify the main use

    It allows parallel execution and waits until all tasks finish before continuing.
  3. Final Answer:

    To run multiple tasks in parallel and wait for all to complete -> Option A
  4. Quick Check:

    TaskGroup = parallel tasks + wait [OK]
Hint: TaskGroup runs tasks together and waits for all [OK]
Common Mistakes:
  • Thinking TaskGroup runs only one task
  • Confusing TaskGroup with error handling
  • Assuming TaskGroup pauses tasks
2. Which of the following is the correct way to add a task inside a TaskGroup in Swift?
easy
A. group.runTask(fetchData())
B. group.createTask(fetchData)
C. group.addTask { await fetchData() }
D. group.startTask { fetchData() }

Solution

  1. Step 1: Recall the method to add tasks

    The correct method to add a task is addTask with a closure.
  2. Step 2: Check syntax correctness

    group.addTask { await fetchData() } uses group.addTask { await fetchData() }, which is the right syntax.
  3. Final Answer:

    group.addTask { await fetchData() } -> Option C
  4. Quick Check:

    Use addTask with closure [OK]
Hint: Use addTask with closure to add work [OK]
Common Mistakes:
  • Using wrong method names like runTask or createTask
  • Not using closure syntax
  • Omitting await inside the task
3. What will be the output of this Swift code using a TaskGroup?
func fetchNumber(_ n: Int) async -> Int {
    return n * 2
}

func runGroup() async {
    await withTaskGroup(of: Int.self) { group in
        for i in 1...3 {
            group.addTask { await fetchNumber(i) }
        }
        var results = [Int]()
        for await result in group {
            results.append(result)
        }
        print(results.sorted())
    }
}

Task {
    await runGroup()
}
medium
A. Compilation error
B. [1, 2, 3]
C. [6, 4, 2]
D. [2, 4, 6]

Solution

  1. Step 1: Understand the task group adds tasks for numbers 1 to 3

    Each task returns the input number multiplied by 2: 2, 4, and 6.
  2. Step 2: Collect results and sort them before printing

    Results are collected in any order but sorted before printing, so output is [2, 4, 6].
  3. Final Answer:

    [2, 4, 6] -> Option D
  4. Quick Check:

    Results doubled and sorted = [2,4,6] [OK]
Hint: Remember to sort results after parallel tasks [OK]
Common Mistakes:
  • Assuming results print in order added
  • Forgetting to await inside addTask
  • Confusing output with original numbers
4. Identify the error in this Swift code using a TaskGroup:
await withTaskGroup(of: Int.self) { group in
    for i in 1...3 {
        group.addTask { fetchNumber(i) }
    }
    for await result in group {
        print(result)
    }
}
Assuming fetchNumber is an async function.
medium
A. Missing await inside addTask closure
B. Cannot use for await with TaskGroup
C. TaskGroup must be declared with var
D. fetchNumber must return Void

Solution

  1. Step 1: Check how fetchNumber is called inside addTask

    fetchNumber is async, so it must be awaited inside the closure.
  2. Step 2: Identify missing await keyword

    The closure calls fetchNumber(i) without await, causing a compile error.
  3. Final Answer:

    Missing await inside addTask closure -> Option A
  4. Quick Check:

    Async calls inside addTask need await [OK]
Hint: Always await async calls inside addTask closures [OK]
Common Mistakes:
  • Forgetting await inside addTask
  • Thinking for await can't be used with TaskGroup
  • Declaring TaskGroup incorrectly
5. You want to fetch data from multiple URLs in parallel using a TaskGroup and collect only the successful results (non-nil). Which approach correctly filters out nil results while running tasks in parallel?
hard
A. Run tasks sequentially inside the group to avoid nil results
B. Add tasks returning optional data, then filter non-nil in for await loop
C. Use addTask with throwing function and catch errors outside group
D. Use withThrowingTaskGroup but ignore errors and collect all results

Solution

  1. Step 1: Understand the goal to run tasks in parallel and filter nil

    Running tasks in parallel with TaskGroup allows concurrency; filtering nil after collecting results is straightforward.
  2. Step 2: Evaluate options for filtering nil results

    Add tasks returning optional data, then filter non-nil in for await loop correctly adds tasks returning optional data and filters non-nil results in the for await loop, matching the goal.
  3. Final Answer:

    Add tasks returning optional data, then filter non-nil in for await loop -> Option B
  4. Quick Check:

    Filter nil after parallel tasks with for await [OK]
Hint: Filter nil results after collecting parallel task outputs [OK]
Common Mistakes:
  • Trying to run tasks sequentially losing parallelism
  • Ignoring errors without filtering nil
  • Misusing throwing task groups for simple filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard