0
0
Swiftprogramming~30 mins

Async functions declaration in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Async functions declaration
📖 Scenario: You are building a simple Swift program that fetches user data asynchronously, simulating a network call.
🎯 Goal: Create an async function to fetch user data and call it properly to print the result.
📋 What You'll Learn
Declare an async function named fetchUserData that returns a String
Inside fetchUserData, simulate a delay using Task.sleep
Create a main async function to call fetchUserData and store the result
Print the fetched user data in main
💡 Why This Matters
🌍 Real World
Async functions are used to perform tasks like fetching data from the internet without freezing the app interface.
💼 Career
Understanding async functions is essential for Swift developers working on apps that need smooth user experiences with network calls or long-running tasks.
Progress0 / 4 steps
1
Create the async function declaration
Declare an async function called fetchUserData that returns a String. Inside the function, return the string "User data loaded".
Swift
Need a hint?

Use func keyword, add async after parentheses, and specify -> String for return type.

2
Add a delay inside the async function
Inside the fetchUserData function, add a delay of 1 second using try? await Task.sleep(nanoseconds: 1_000_000_000) before returning the string.
Swift
Need a hint?

Use try? await Task.sleep(nanoseconds: 1_000_000_000) to pause for 1 second.

3
Create an async main function to call fetchUserData
Declare an async function called main. Inside it, call fetchUserData() using await and store the result in a variable named userData.
Swift
Need a hint?

Use func main() async and call await fetchUserData() storing result in userData.

4
Print the fetched user data
Inside the main function, add a print statement to display the userData variable. Then, call Task { await main() } to run the async main function.
Swift
Need a hint?

Use print(userData) inside main and start it with Task { await main() }.