Challenge - 5 Problems
TaskGroup Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
Understanding TaskGroup concurrency behavior
Consider this Swift code using
TaskGroup. What will be printed first?iOS Swift
func testTaskGroup() async { await withTaskGroup(of: String.self) { group in group.addTask { "First" } group.addTask { "Second" } for await result in group { print(result) break } } print("Done") } Task { await testTaskGroup() }
Attempts:
2 left
💡 Hint
The first completed task result is printed before breaking the loop.
✗ Incorrect
The
for await loop prints the first completed task's result, which is "First" here, then breaks. After the group ends, "Done" is printed.❓ lifecycle
intermediate2:00remaining
Task cancellation inside TaskGroup
What happens if a task inside a
TaskGroup calls Task.cancel() on itself?iOS Swift
func cancelInsideGroup() async { await withTaskGroup(of: Void.self) { group in group.addTask { Task.cancel() print("Cancelled") } group.addTask { print("Running") } } } Task { await cancelInsideGroup() }
Attempts:
2 left
💡 Hint
Cancellation does not stop the current task immediately.
✗ Incorrect
Calling
Task.cancel() marks the task as cancelled but does not stop execution immediately, so "Cancelled" is printed. The other task runs normally.📝 Syntax
advanced2:00remaining
Correct syntax for adding tasks in TaskGroup
Which option correctly adds a task returning an Int in a
TaskGroup?iOS Swift
func addTaskExample() async { await withTaskGroup(of: Int.self) { group in // Add a task here } }
Attempts:
2 left
💡 Hint
The closure can return the value directly without return keyword.
✗ Incorrect
Option A is correct because the closure returns 42 directly. Option A is valid Swift but redundant here. Option A is invalid because 'await' is not needed for a literal. Option A is invalid syntax.
🔧 Debug
advanced2:00remaining
Why does this TaskGroup code deadlock?
Given this code, why does it deadlock?
iOS Swift
func deadlockExample() async { await withTaskGroup(of: Void.self) { group in group.addTask { await deadlockExample() // recursive call } } } Task { await deadlockExample() }
Attempts:
2 left
💡 Hint
Think about waiting inside the group for itself to finish.
✗ Incorrect
The recursive call awaits the same TaskGroup to finish, causing a deadlock cycle where the group waits on itself.
🧠 Conceptual
expert2:00remaining
TaskGroup result ordering guarantee
Which statement about the order of results from
withTaskGroup is true?Attempts:
2 left
💡 Hint
Think about concurrency and task completion timing.
✗ Incorrect
TaskGroup yields results as tasks complete, so order depends on completion, not addition order.