Bird
Raised Fist0
iOS Swiftmobile~20 mins

Async functions in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Async Data Loader
This screen fetches a random joke from an online API asynchronously and displays it. It shows a loading spinner while waiting for the data.
Target UI
-------------------------
| Async Data Loader     |
-------------------------
|                       |
|   [Loading Spinner]    |
|                       |
|                       |
|                       |
|                       |
|                       |
-------------------------
Use Swift async/await to fetch data from https://official-joke-api.appspot.com/random_joke
Show a loading spinner while fetching
Display the joke's setup and punchline after loading
Handle errors by showing an error message
Use SwiftUI for UI components
Starter Code
iOS Swift
import SwiftUI

struct AsyncDataLoaderView: View {
    @State private var joke: String = ""
    @State private var isLoading = false
    @State private var errorMessage: String? = nil

    var body: some View {
        VStack {
            // TODO: Add loading spinner, joke text, and error message here
        }
        .padding()
        .task {
            // TODO: Call async function to fetch joke here
        }
    }

    // TODO: Add async function to fetch joke here
}

struct AsyncDataLoaderView_Previews: PreviewProvider {
    static var previews: some View {
        AsyncDataLoaderView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

struct AsyncDataLoaderView: View {
    @State private var joke: String = ""
    @State private var isLoading = false
    @State private var errorMessage: String? = nil

    var body: some View {
        VStack(spacing: 20) {
            if isLoading {
                ProgressView("Loading...")
                    .progressViewStyle(CircularProgressViewStyle())
                    .accessibilityLabel("Loading joke")
            } else if let error = errorMessage {
                Text("Error: \(error)")
                    .foregroundColor(.red)
                    .multilineTextAlignment(.center)
                    .accessibilityLabel("Error message")
            } else if !joke.isEmpty {
                Text(joke)
                    .font(.title3)
                    .multilineTextAlignment(.center)
                    .accessibilityLabel("Joke")
            } else {
                Text("No joke loaded.")
                    .foregroundColor(.gray)
            }
        }
        .padding()
        .task {
            await fetchJoke()
        }
    }

    func fetchJoke() async {
        isLoading = true
        errorMessage = nil
        joke = ""

        guard let url = URL(string: "https://official-joke-api.appspot.com/random_joke") else {
            errorMessage = "Invalid URL"
            isLoading = false
            return
        }

        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            if let decoded = try? JSONDecoder().decode(Joke.self, from: data) {
                joke = "\(decoded.setup)\n\n\(decoded.punchline)"
            } else {
                errorMessage = "Failed to decode joke"
            }
        } catch {
            errorMessage = error.localizedDescription
        }

        isLoading = false
    }
}

struct Joke: Decodable {
    let setup: String
    let punchline: String
}

struct AsyncDataLoaderView_Previews: PreviewProvider {
    static var previews: some View {
        AsyncDataLoaderView()
    }
}

This solution uses SwiftUI's .task modifier to start fetching the joke asynchronously when the view appears. The fetchJoke() function uses Swift's async/await with URLSession.shared.data(from:) to get data from the joke API.

While loading, a ProgressView spinner is shown. If the fetch succeeds, the joke's setup and punchline are displayed. If an error occurs, an error message is shown in red.

Accessibility labels are added for screen readers. The UI updates reactively based on the state variables isLoading, joke, and errorMessage.

Final Result
Completed Screen
-------------------------
| Async Data Loader     |
-------------------------
|                       |
|   (spinner animates)  |
|       Loading...       |
|                       |
|                       |
|                       |
-------------------------

After loading:
-------------------------
| Async Data Loader     |
-------------------------
|                       |
| Why did the chicken   |
| cross the road?       |
|                       |
| To get to the other   |
| side!                 |
-------------------------
When the screen appears, a spinner shows while the joke loads.
After loading, the joke text replaces the spinner.
If the network fails, an error message appears in red.
Stretch Goal
Add a button to reload a new joke on demand.
💡 Hint
Add a Button below the joke text that calls fetchJoke() asynchronously when tapped.

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