Bird
0
0

What is wrong with this Swift code snippet?

medium📝 Debug Q7 of 15
iOS Swift - Concurrency
What is wrong with this Swift code snippet?
await withTaskGroup(of: Int.self) { group in
  group.addTask { 5 }
  group.addTask { 10 }
  var total = 0
  for value in group {
    total += value
  }
  print(total)
}
ACannot add tasks returning Int
BMissing await keyword before for loop iteration
CTaskGroup must be declared with var keyword
Dprint statement must be inside a Task
Step-by-Step Solution
Solution:
  1. Step 1: Review for-await syntax

    When iterating over a TaskGroup, the for loop must be 'for await' to await each task's result.
  2. Step 2: Identify missing await

    The code uses 'for value in group' instead of 'for await value in group'.
  3. Final Answer:

    Missing await keyword before for loop iteration -> Option B
  4. Quick Check:

    Use 'for await' to iterate TaskGroup results [OK]
Quick Trick: Always use 'for await' to iterate TaskGroup results [OK]
Common Mistakes:
  • Using regular for loop without await
  • Thinking addTask can't return values
  • Misplacing print statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes