Bird
Raised Fist0
iOS Swiftmobile~20 mins

Async functions in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What will this SwiftUI view display after 2 seconds?

Consider this SwiftUI view using an async function to fetch data:

struct ContentView: View {
  @State private var message = "Loading..."

  var body: some View {
    Text(message)
      .task {
        message = await fetchMessage()
      }
  }

  func fetchMessage() async -> String {
    try? await Task.sleep(nanoseconds: 2_000_000_000)
    return "Hello, async!"
  }
}

What text will be shown on screen after 2 seconds?

iOS Swift
struct ContentView: View {
  @State private var message = "Loading..."

  var body: some View {
    Text(message)
      .task {
        message = await fetchMessage()
      }
  }

  func fetchMessage() async -> String {
    try? await Task.sleep(nanoseconds: 2_000_000_000)
    return "Hello, async!"
  }
}
AThe app crashes due to missing await
B"Hello, async!" replaces "Loading..." after 2 seconds
C"Loading..." remains forever
D"Loading..." changes to empty string after 2 seconds
Attempts:
2 left
💡 Hint

Think about what the .task modifier does and how await pauses the function.

❓ lifecycle
intermediate
2:00remaining
What happens if you call an async function without await in Swift?

Given this code snippet:

func loadData() async {
  print("Start loading")
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  print("Finished loading")
}

func example() {
  loadData()
  print("After loadData call")
}

What is the order of printed lines when example() is called?

iOS Swift
func loadData() async {
  print("Start loading")
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  print("Finished loading")
}

func example() {
  loadData()
  print("After loadData call")
}
AStart loading\nFinished loading\nAfter loadData call
BCompilation error: missing await
CStart loading\nAfter loadData call\nFinished loading
DAfter loadData call\nStart loading\nFinished loading
Attempts:
2 left
💡 Hint

Remember that calling an async function without await starts it but does not wait for it to finish.

📝 Syntax
advanced
2:00remaining
Which option correctly defines an async function that returns an Int after delay?

Choose the correct Swift function definition that waits 1 second and returns 42 asynchronously.

A
func getNumber() async -> Int {
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  return 42
}
B
async func getNumber() -> Int {
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  return 42
}
C
func getNumber() -> async Int {
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  return 42
}
D
func async getNumber() -> Int {
  try? await Task.sleep(nanoseconds: 1_000_000_000)
  return 42
}
Attempts:
2 left
💡 Hint

In Swift, the async keyword goes after the function parentheses.

🔧 Debug
advanced
2:00remaining
Why does this async function cause a runtime error?

Analyze this code snippet:

func fetchData() async -> String {
  DispatchQueue.global().async {
    print("Fetching data")
  }
  return "Done"
}

When calling await fetchData(), why might this cause unexpected behavior?

iOS Swift
func fetchData() async -> String {
  DispatchQueue.global().async {
    print("Fetching data")
  }
  return "Done"
}
AThe function causes a compile-time error because DispatchQueue cannot be used in async functions
BThe function throws a runtime exception due to missing await
CThe function blocks the main thread indefinitely
DThe function returns immediately before the async block finishes, causing race conditions
Attempts:
2 left
💡 Hint

Think about how DispatchQueue.global().async works compared to Swift concurrency.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of Swift async/await over completion handlers?

Choose the best explanation for why Swift introduced async/await instead of using completion handlers for asynchronous code.

AAsync/await makes asynchronous code look and behave like synchronous code, improving readability and reducing callback nesting
BAsync/await runs all code on the main thread, improving UI responsiveness
CAsync/await eliminates the need for error handling in asynchronous code
DAsync/await automatically parallelizes all asynchronous tasks without developer control
Attempts:
2 left
💡 Hint

Think about how code looks and feels when using async/await compared to nested callbacks.

Practice

(1/5)
1. What does marking a function with async in Swift mean?
easy
A. The function cannot call other functions.
B. The function runs only once and then stops.
C. The function must return an integer value.
D. The function can pause and resume without blocking the app's main thread.

Solution

  1. Step 1: Understand async function behavior

    Async functions allow pausing and resuming work without freezing the app's main thread.
  2. Step 2: Compare options with async meaning

    Only The function can pause and resume without blocking the app's main thread. correctly describes this behavior; others are unrelated or incorrect.
  3. Final Answer:

    The function can pause and resume without blocking the app's main thread. -> Option D
  4. Quick Check:

    Async means non-blocking pause/resume = A [OK]
Hint: Async means work happens without freezing UI [OK]
Common Mistakes:
  • Thinking async means the function runs only once
  • Confusing async with return types
  • Believing async functions cannot call others
2. Which of the following is the correct way to declare an async function in Swift?
easy
A. func fetchData() async throws -> String {}
B. async func fetchData() -> String {}
C. func async fetchData() throws -> String {}
D. func fetchData() throws async String {}

Solution

  1. Step 1: Recall Swift async function syntax

    In Swift, async comes after the parameter list and before the return type.
  2. Step 2: Match options to correct syntax

    Only func fetchData() async throws -> String {} matches the correct syntax: func name() async throws -> Type {}.
  3. Final Answer:

    func fetchData() async throws -> String {} -> Option A
  4. Quick Check:

    Async keyword after () = C [OK]
Hint: Async keyword goes after function parameters () [OK]
Common Mistakes:
  • Placing async before func keyword
  • Mixing async and throws order
  • Putting async after return type
3. What will be printed by this Swift code?
func fetchNumber() async -> Int {
  return 42
}

Task {
  let number = await fetchNumber()
  print(number)
}
medium
A. 42
B. nil
C. Task
D. Compilation error

Solution

  1. Step 1: Understand async function return

    The async function fetchNumber() returns 42 as an Int.
  2. Step 2: Await call inside Task and print

    The await keyword waits for the async function to finish, then prints 42.
  3. Final Answer:

    42 -> Option A
  4. Quick Check:

    Await fetch returns 42 printed = D [OK]
Hint: Await pauses until async returns value [OK]
Common Mistakes:
  • Expecting nil because of async
  • Thinking Task prints itself
  • Assuming compilation error without await
4. Identify the error in this Swift async code:
func loadData() async -> String {
  return "Data"
}

let result = loadData()
print(result)
medium
A. Async functions cannot return String
B. Missing await keyword when calling async function
C. Function must be marked throws
D. Cannot print async function result

Solution

  1. Step 1: Check async function call

    Async functions must be called with await to get their result.
  2. Step 2: Identify missing await

    The code calls loadData() without await, causing a compile error.
  3. Final Answer:

    Missing await keyword when calling async function -> Option B
  4. Quick Check:

    Call async with await = B [OK]
Hint: Always use await when calling async functions [OK]
Common Mistakes:
  • Calling async functions without await
  • Thinking async functions can't return String
  • Assuming print can't show async results
5. You want to fetch user data and then fetch user image asynchronously in Swift. Which code correctly waits for both tasks in order?
hard
A. async func loadUser() { let data = fetchUserData() let image = fetchUserImage(data.id) print(image) }
B. func loadUser() { let data = fetchUserData() let image = fetchUserImage(data.id) print(image) }
C. async func loadUser() { let data = await fetchUserData() let image = await fetchUserImage(data.id) print(image) }
D. async func loadUser() { let data = await fetchUserData() let image = fetchUserImage(data.id) print(image) }

Solution

  1. Step 1: Understand async calls order

    Both fetchUserData() and fetchUserImage() are async and must be awaited to complete before next step.
  2. Step 2: Check which code awaits both calls

    Only async func loadUser() { let data = await fetchUserData() let image = await fetchUserImage(data.id) print(image) } awaits both calls in order, ensuring data is ready before fetching image.
  3. Final Answer:

    async func loadUser() { let data = await fetchUserData() let image = await fetchUserImage(data.id) print(image) } -> Option C
  4. Quick Check:

    Await each async call in order = A [OK]
Hint: Await each async call to run sequentially [OK]
Common Mistakes:
  • Not awaiting async calls
  • Calling async functions without async keyword
  • Mixing sync and async calls incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard