Bird
Raised Fist0
iOS Swiftmobile~20 mins

Await keyword in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Async Greeting Screen
This screen shows a button that fetches a greeting message asynchronously using the await keyword and displays it.
Target UI
-------------------------
| Async Greeting Screen |
-------------------------
|                       |
|  [Fetch Greeting]     |
|                       |
|  Greeting:            |
|                       |
|                       |
-------------------------
Add a button labeled 'Fetch Greeting'.
When tapped, it calls an async function that waits 2 seconds and returns a greeting string.
Display the greeting text below the button after fetching.
Show a loading indicator while waiting.
Starter Code
iOS Swift
import SwiftUI

struct AsyncGreetingView: View {
    @State private var greeting: String = ""
    @State private var isLoading: Bool = false

    var body: some View {
        VStack(spacing: 20) {
            Text("Async Greeting Screen")
                .font(.title)

            Button("Fetch Greeting") {
                // TODO: Call async function here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            if isLoading {
                ProgressView()
            }

            Text("Greeting: \(greeting)")
                .font(.headline)

            Spacer()
        }
        .padding()
    }

    // TODO: Add async function to fetch greeting
}

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

struct AsyncGreetingView: View {
    @State private var greeting: String = ""
    @State private var isLoading: Bool = false

    var body: some View {
        VStack(spacing: 20) {
            Text("Async Greeting Screen")
                .font(.title)

            Button("Fetch Greeting") {
                Task {
                    isLoading = true
                    greeting = await fetchGreeting()
                    isLoading = false
                }
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            if isLoading {
                ProgressView()
            }

            Text("Greeting: \(greeting)")
                .font(.headline)

            Spacer()
        }
        .padding()
    }

    func fetchGreeting() async -> String {
        try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
        return "Hello from async!"
    }
}

struct AsyncGreetingView_Previews: PreviewProvider {
    static var previews: some View {
        AsyncGreetingView()
    }
}

We created an async function fetchGreeting() that waits 2 seconds using Task.sleep and then returns a greeting string.

The button action uses Task to run async code. Inside, it sets isLoading to true, then calls await fetchGreeting() to wait for the greeting, updates the greeting state, and finally sets isLoading to false.

This shows a loading spinner while waiting and updates the UI with the greeting once ready.

Final Result
Completed Screen
-------------------------
| Async Greeting Screen |
-------------------------
|                       |
|  [Fetch Greeting]     |
|                       |
|  Loading...           |
|                       |
|  Greeting: Hello from |
|  async!               |
-------------------------
User taps 'Fetch Greeting' button.
A spinner appears below the button indicating loading.
After 2 seconds, spinner disappears and greeting text updates to 'Hello from async!'.
Stretch Goal
Add error handling to show an alert if fetching the greeting fails.
💡 Hint
Use try? with Task.sleep and add a Bool state to show an Alert with .alert modifier.

Practice

(1/5)
1. What does the await keyword do in Swift's async functions?
easy
A. It converts a synchronous function to asynchronous.
B. It makes the function run faster.
C. It pauses the function until the async task completes.
D. It cancels the async task immediately.

Solution

  1. Step 1: Understand the role of await

    The await keyword pauses the execution of an async function until the awaited task finishes.
  2. Step 2: Compare other options

    Options B, C, and D describe behaviors that await does not perform.
  3. Final Answer:

    It pauses the function until the async task completes. -> Option C
  4. Quick Check:

    await pauses async tasks = A [OK]
Hint: Remember: await waits for task completion before continuing [OK]
Common Mistakes:
  • Thinking await speeds up the function
  • Using await outside async functions
  • Confusing await with task cancellation
2. Which of the following is the correct way to declare an async function that uses await inside it?
easy
A. func fetchData() async { let data = await loadData() }
B. func fetchData() { let data = await loadData() }
C. async func fetchData() { let data = await loadData() }
D. func fetchData() async await { let data = loadData() }

Solution

  1. Step 1: Check async function declaration syntax

    In Swift, the correct syntax is func name() async {} to declare an async function.
  2. Step 2: Verify usage of await inside async function

    func fetchData() async { let data = await loadData() } correctly uses await inside an async function. Options B, C, and D have syntax errors.
  3. Final Answer:

    func fetchData() async { let data = await loadData() } -> Option A
  4. Quick Check:

    Async function syntax = A [OK]
Hint: Async functions must have 'async' keyword before braces [OK]
Common Mistakes:
  • Omitting async keyword in function declaration
  • Placing async before func keyword
  • Adding await in function signature
3. What will be printed by this Swift code?
func fetchNumber() async -> Int {
  return 5
}

func printNumber() async {
  let number = await fetchNumber()
  print(number)
}

Task {
  await printNumber()
}
medium
A. No output, code has syntax error
B. 5
C. 0
D. The program crashes

Solution

  1. Step 1: Understand async function behavior

    The function fetchNumber() returns 5 asynchronously. Using await waits for this result.
  2. Step 2: Trace the print statement

    The printNumber() function awaits fetchNumber() and prints the returned value 5.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Await returns value before print = C [OK]
Hint: Await pauses until value returns, then prints it [OK]
Common Mistakes:
  • Expecting 0 because of async
  • Thinking code crashes without main thread
  • Confusing async function call without await
4. Identify the error in this Swift code snippet:
func loadData() async -> String {
  return "Data"
}

func showData() {
  let result = await loadData()
  print(result)
}
medium
A. Missing async keyword in showData function declaration.
B. print statement is not allowed inside async functions.
C. loadData function should not return String.
D. Cannot use await inside a non-async function.

Solution

  1. Step 1: Check function declarations and await usage

    The function showData() is not marked async but uses await, which is invalid.
  2. Step 2: Understand await usage rules

    In Swift, await can only be used inside async functions. So showData() must be async to use await.
  3. Final Answer:

    Cannot use await inside a non-async function. -> Option D
  4. Quick Check:

    Await only in async functions = D [OK]
Hint: Await requires async function context [OK]
Common Mistakes:
  • Forgetting to mark function async when using await
  • Thinking await works in normal functions
  • Misunderstanding return types with async
5. You want to fetch user data and then fetch user posts, both are async functions. Which code correctly waits for both tasks in order using await?
hard
A. func loadUserData() async { let user = await fetchUser() let posts = await fetchPosts(user.id) print(posts) }
B. func loadUserData() async { let user = fetchUser() let posts = fetchPosts(user.id) print(posts) }
C. func loadUserData() { let user = await fetchUser() let posts = await fetchPosts(user.id) print(posts) }
D. func loadUserData() async { let user = await fetchUser() let posts = fetchPosts(user.id) print(posts) }

Solution

  1. Step 1: Confirm async function declaration

    The function must be marked async to use await inside it, so options A and D are candidates.
  2. Step 2: Check await usage for both async calls

    func loadUserData() async { let user = await fetchUser() let posts = await fetchPosts(user.id) print(posts) } awaits both fetchUser() and fetchPosts(), ensuring sequential completion. func loadUserData() async { let user = await fetchUser() let posts = fetchPosts(user.id) print(posts) } misses await on fetchPosts().
  3. Final Answer:

    func loadUserData() async { let user = await fetchUser() let posts = await fetchPosts(user.id) print(posts) } -> Option A
  4. Quick Check:

    Await both async calls in async function = B [OK]
Hint: Await each async call to run in order inside async function [OK]
Common Mistakes:
  • Forgetting await on second async call
  • Not marking function async
  • Calling async functions without await
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