Bird
0
0

What is the issue with this Swift code using structured concurrency?

medium📝 Debug Q6 of 15
iOS Swift - Concurrency
What is the issue with this Swift code using structured concurrency?
func loadStrings() async {
  let group = withTaskGroup(of: String.self) { group in
    group.addTask { "Swift" }
  }
  print(await group.next())
}
AThe group variable is not awaited and does not return a TaskGroup instance
BThe addTask closure must be marked async
Cgroup.next() cannot be awaited inside the function
DThe function must return a value
Step-by-Step Solution
Solution:
  1. Step 1: Understand withTaskGroup return type

    The withTaskGroup function is async and returns the result of its closure, not a TaskGroup instance.
  2. Step 2: Analyze the code

    Assigning let group = withTaskGroup {} is incorrect because group is not a TaskGroup but the closure's return value.
  3. Step 3: Correct usage

    Use await withTaskGroup and handle the group inside the closure; do not assign it to a variable.
  4. Final Answer:

    The group variable is not awaited and does not represent a TaskGroup instance -> Option A
  5. Quick Check:

    withTaskGroup returns closure result, not a TaskGroup object [OK]
Quick Trick: withTaskGroup returns closure result, not a TaskGroup instance [OK]
Common Mistakes:
  • Assigning withTaskGroup to a variable expecting a TaskGroup
  • Not awaiting withTaskGroup
  • Trying to use group.next() outside the closure

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes