Pick the fix
You need avatars for ids: [UUID] (length known only at runtime), fetched in parallel. Which code?
Hint 1 of 2
Is the number of calls known when you write the code?
Hint 2 of 2
Which API lets you add children in a loop?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B withTaskGroup(of: (UUID, UIImage).self) { group in for id in ids { group.addTask { (id, await fetch(id)) } } ... }
Correct. A group handles a runtime number of children and keeps them structured.
Why not the others?
- A
for id in ids { async let a = fetch(id); images.append(await a) }. Eachasync letbelongs to one loop iteration and is awaited before the next starts, so this runs one at a time. - C
let tasks = ids.map { id in Task { await fetch(id) } }. It runs in parallel, but the tasks are unstructured: leaving the screen won't cancel them. - D
let images = await ids.map { await fetch($0) }.maptakes a synchronous closure, so you can'tawaitinside it. This doesn't compile.
Text version
| Version | What runs when | Finishes at |
|---|---|---|
| async let in a loop |
| t = 3.0 s |
| TaskGroup |
| t = 1.0 s |