Bird
0
0

Given these async functions:

hard📝 Application Q9 of 15
iOS Swift - Concurrency
Given these async functions:
func fetchA() async -> Int { 1 }
func fetchB() async -> Int { 2 }

func combined() async -> Int {
  let a = await fetchA()
  let b = await fetchB()
  return a + b
}

How can you optimize combined() to run both fetches concurrently using await?
AUse DispatchQueue to run fetches concurrently
BCall fetchA() and fetchB() without await and add results
CUse async let: <br>async let a = fetchA()<br>async let b = fetchB()<br>return await a + await b
DAwait fetchA() then fetchB() sequentially as is
Step-by-Step Solution
Solution:
  1. Step 1: Understand concurrency with async let

    Using async let starts both async calls concurrently.
  2. Step 2: Await both results before returning sum

    Awaiting a and b after starting them concurrently improves performance.
  3. Final Answer:

    Use async let:
    async let a = fetchA()
    async let b = fetchB()
    return await a + await b
    -> Option C
  4. Quick Check:

    async let runs concurrent awaits [OK]
Quick Trick: Use async let for concurrent awaits [OK]
Common Mistakes:
  • Awaiting calls sequentially
  • Not awaiting async let variables
  • Using DispatchQueue instead of async let

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes