ConcurrencyMidMCQ
What is `TaskGroup` and when would you use it?
Test your knowledge:
Explanation & Code
Answer:
TaskGroup lets you run multiple async tasks in parallel and collect all their results. Use it when you have a dynamic number of parallel operations.
Code Example:
func fetchAllUsers(ids: [Int]) async throws -> [User] {
try await withThrowingTaskGroup(of: User.self) { group in
for id in ids {
group.addTask {
try await fetchUser(id: id)
}
}
var users: [User] = []
for try await user in group {
users.append(user)
}
return users
}
}
// All fetches run in parallel — much faster than sequential await
let users = try await fetchAllUsers(ids: [1, 2, 3, 4, 5])
Key Points:
withTaskGroupfor non-throwing taskswithThrowingTaskGroupwhen tasks can throw- Results arrive in completion order, not the order tasks were added
Rate your understanding: