Challenge - 5 Problems
Swift Task Group Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of concurrent task group with async sleeps
What is the output of this Swift code using task groups for parallel execution?
Swift
import Foundation func testTaskGroup() async { await withThrowingTaskGroup(of: String.self) { group in group.addTask { try await Task.sleep(nanoseconds: 1_000_000_000) return "First" } group.addTask { try await Task.sleep(nanoseconds: 500_000_000) return "Second" } group.addTask { return "Third" } for try await result in group { print(result) } }} Task { await testTaskGroup() } RunLoop.main.run()
Attempts:
2 left
💡 Hint
Remember that tasks in a task group complete independently and results are received as they finish.
✗ Incorrect
The task that returns "Third" has no delay and finishes first. The task with 0.5s delay finishes second, and the 1s delay task finishes last. The for-await loop prints results as tasks complete.
🧠 Conceptual
intermediate1:30remaining
Understanding task group cancellation behavior
In Swift concurrency, what happens to remaining tasks in a task group if one task throws an error?
Attempts:
2 left
💡 Hint
Think about how Swift handles errors in concurrent task groups to avoid wasted work.
✗ Incorrect
When a task in a task group throws, Swift cancels all remaining tasks immediately and propagates the error to the caller.
🔧 Debug
advanced2:00remaining
Identify the error in this task group code
What error does this Swift code produce?
Swift
import Foundation func runTasks() async throws { await withThrowingTaskGroup(of: Int.self) { group in for i in 1...3 { group.addTask { if i == 2 { throw NSError(domain: "Test", code: 1) } return i } } for try await value in group { print(value) } }} Task { do { try await runTasks() } catch { print("Error: \(error)") } } RunLoop.main.run()
Attempts:
2 left
💡 Hint
Check if the closure passed to addTask supports throwing errors.
✗ Incorrect
The original code causes a compilation error because the closure passed to addTask is non-throwing but contains a 'throw' statement. Changing to withThrowingTaskGroup and marking runTasks as async throws fixes this.
📝 Syntax
advanced1:30remaining
Correct syntax for adding tasks with return values in a task group
Which option shows the correct syntax to add tasks returning Int values in a Swift task group?
Swift
await withTaskGroup(of: Int.self) { group in // Add tasks here }
Attempts:
2 left
💡 Hint
Remember the closure passed to addTask can be async but does not require 'await' for returning a value.
✗ Incorrect
Option C correctly adds a task returning 5. Option C misuses 'await' on a literal. Option C uses invalid syntax. Option C tries to throw a non-error value.
🚀 Application
expert2:30remaining
Calculate sum of squares using task groups concurrently
Given this Swift code, what is the value of 'total' after execution?
Swift
import Foundation func sumOfSquares(_ numbers: [Int]) async -> Int { await withTaskGroup(of: Int.self) { group in for number in numbers { group.addTask { number * number } } var sum = 0 for await value in group { sum += value } return sum } } Task { let total = await sumOfSquares([1, 2, 3, 4]) print(total) } RunLoop.main.run()
Attempts:
2 left
💡 Hint
Calculate each number squared and add them all: 1² + 2² + 3² + 4².
✗ Incorrect
1*1=1, 2*2=4, 3*3=9, 4*4=16; sum is 1+4+9+16=30.