Bird
0
0

How do you correctly create a Task in Swift that asynchronously returns the integer 42?

easy📝 Syntax Q3 of 15
iOS Swift - Concurrency
How do you correctly create a Task in Swift that asynchronously returns the integer 42?
Alet task = Task.async { return 42 }
Blet task = Task<Int> { print(42) }
Clet task = Task.run { 42 }
Dlet task = Task { return 42 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand Task creation syntax

    In Swift concurrency, a Task is created using Task { ... } with a closure that returns the desired value asynchronously.
  2. Step 2: Analyze options

    let task = Task { return 42 } correctly uses Task { return 42 }. let task = Task { print(42) } incorrectly uses Task and prints instead of returning. let task = Task.run { 42 } uses a non-existent Task.run method. let task = Task.async { return 42 } uses Task.async which is invalid.
  3. Final Answer:

    let task = Task { return 42 } -> Option D
  4. Quick Check:

    Task creation uses Task { ... } syntax [OK]
Quick Trick: Use Task { } with a closure returning the value [OK]
Common Mistakes:
  • Using non-existent Task methods like Task.run or Task.async
  • Confusing print with return inside Task closure
  • Specifying generic type incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes