Bird
0
0

Consider this Swift code snippet using TaskGroup:

medium📝 Predict Output Q4 of 15
iOS Swift - Concurrency
Consider this Swift code snippet using TaskGroup:
func runTasks() async {
  await withTaskGroup(of: Int.self) { group in
    group.addTask { 1 }
    group.addTask { 2 }
    group.addTask { 3 }
    var sum = 0
    for await value in group {
      sum += value
    }
    print(sum)
  }
}
What will be printed when runTasks() is called?
A3
B6
C123
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand TaskGroup behavior

    The group runs three tasks returning 1, 2, and 3 asynchronously.
  2. Step 2: Sum values from group

    The for-await loop sums all returned values: 1 + 2 + 3 = 6.
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    Sum of TaskGroup results = 6 [OK]
Quick Trick: TaskGroup collects all results; sum them to get total [OK]
Common Mistakes:
  • Thinking values concatenate as strings
  • Assuming only last value is printed
  • Ignoring asynchronous iteration

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes