Bird
0
0

You want to collect the first 3 values from an async sequence updates into an array. Which code correctly does this?

hard📝 Application Q15 of 15
iOS Swift - Concurrency
You want to collect the first 3 values from an async sequence updates into an array. Which code correctly does this?
Avar results = [] for await update in updates { results.append(update) if results.count == 3 { break } }
Bvar results = [] for update in updates { results.append(update) if results.count == 3 { break } }
Cvar results = [] while let update = await updates.next() { results.append(update) if results.count == 3 { break } }
Dvar results = [] updates.forEach { update in results.append(update) if results.count == 3 { break } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand async sequence iteration and breaking

    Use 'for await' to iterate async sequences and break when count reaches 3.
  2. Step 2: Evaluate each option

    var results = [] for await update in updates { results.append(update) if results.count == 3 { break } } uses 'for await' with break after 3 items, correct. var results = [] for update in updates { results.append(update) if results.count == 3 { break } } lacks 'await'. var results = [] while let update = await updates.next() { results.append(update) if results.count == 3 { break } } uses invalid syntax for async sequences. var results = [] updates.forEach { update in results.append(update) if results.count == 3 { break } } uses 'forEach' which doesn't support async iteration or breaking.
  3. Final Answer:

    var results = [] for await update in updates { results.append(update) if results.count == 3 { break } } -> Option A
  4. Quick Check:

    Use 'for await' and break after 3 items [OK]
Quick Trick: Use 'for await' and break after collecting 3 items [OK]
Common Mistakes:
  • Omitting 'await' in the loop
  • Using synchronous loops on async sequences
  • Trying to use 'forEach' with async sequences

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes