0
0
Swiftprogramming~15 mins

Await for calling async functions in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Await for calling async functions
📖 Scenario: You are building a simple Swift program that fetches user data asynchronously, simulating a network call.
🎯 Goal: Learn how to call an async function and use await to get its result properly.
📋 What You'll Learn
Create an async function called fetchUserName() that returns a String
Create a variable called userName to store the result of calling fetchUserName()
Use await keyword to wait for the async function result
Print the userName variable
💡 Why This Matters
🌍 Real World
Async functions are used to fetch data from the internet or perform tasks that take time without freezing the app.
💼 Career
Understanding async/await is essential for modern Swift development, especially for apps that communicate with servers or do background work.
Progress0 / 4 steps
1
Create the async function
Write an async function called fetchUserName() that returns a String "Alice" after a short delay using Task.sleep.
Swift
Need a hint?

Use async keyword in the function signature and Task.sleep(nanoseconds:) to simulate delay.

2
Create a variable to hold the user name
Create a variable called userName of type String and initialize it with an empty string "".
Swift
Need a hint?

Declare userName as a String variable and set it to an empty string.

3
Call the async function with await
Inside an async context, assign the result of calling fetchUserName() using await to the variable userName.
Swift
Need a hint?

Use await before calling fetchUserName() inside the Task closure.

4
Print the user name
Inside the same async Task block, print the value of userName using print(userName).
Swift
Need a hint?

Use print(userName) inside the Task block to show the result.