📖 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
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
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
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
Hint
Use print(userData) inside main and start it with Task { await main() }.
Practice
(1/5)
1. What does the async keyword do when declaring a function in Swift?
easy
A. It marks the function as able to pause and wait for asynchronous tasks.
B. It makes the function run faster by using multiple threads automatically.
C. It forces the function to run only on the main thread.
D. It converts the function into a synchronous blocking call.
Solution
Step 1: Understand the purpose of async
The async keyword tells Swift that the function can pause its work to wait for other tasks without blocking the whole program.
Step 2: Compare with other options
The other options describe behaviors that async does not do: it does not automatically use multiple threads, does not restrict to main thread, and does not block execution.
Final Answer:
It marks the function as able to pause and wait for asynchronous tasks. -> Option A
Quick Check:
async means function can pause and wait [OK]
Hint: Async means function can pause and wait for tasks [OK]
Common Mistakes:
Thinking async makes function run faster automatically
Confusing async with threading
Assuming async blocks the main thread
2. Which of the following is the correct way to declare an async function in Swift?
easy
A. func fetchData() throws async -> String {}
B. async func fetchData() throws -> String {}
C. func async fetchData() throws -> String {}
D. func fetchData() async throws -> String {}
Solution
Step 1: Recall Swift async function syntax
In Swift, the async keyword comes after the function parentheses and before any throws keyword.
Step 2: Check each option
The correct syntax is func fetchData() async throws -> String {}. The other options place async incorrectly (before func, between func and name, or after throws).
Final Answer:
func fetchData() async throws -> String {} -> Option D
B. Missing await keyword inside the function body.
C. Function must return Void if marked async.
D. Cannot combine throws with async.
Solution
Step 1: Check correct order of async and throws
In Swift, async must come before throws in the function declaration.
Step 2: Verify other options
Missing await keyword inside the function body. is incorrect because await is only needed when calling other async functions. Function must return Void if marked async. is wrong; async functions can return any type. Cannot combine throws with async. is false; async and throws can be combined.
Final Answer:
The order of throws and async is incorrect. -> Option A
Quick Check:
async comes before throws in declaration [OK]
Hint: Put async before throws in function declaration [OK]
Common Mistakes:
Swapping async and throws order
Expecting await inside function without async calls
Thinking async functions must return Void
5. You want to write an async function fetchUsernames() that calls two async functions fetchFromServer() and fetchFromCache() and returns the first non-empty result. Which is the correct way to declare and use fetchUsernames()?
hard
A. func fetchUsernames() async -> [String] {
if let server = await fetchFromServer(), !server.isEmpty {
return server
}
let cache = await fetchFromCache()
return cache
}
B. async func fetchUsernames() -> [String] {
let server = fetchFromServer()
if !server.isEmpty {
return server
}
return fetchFromCache()
}
C. func fetchUsernames() async throws -> [String] {
let server = try await fetchFromServer()
if !server.isEmpty {
return server
}
return try await fetchFromCache()
}
D. func fetchUsernames() throws async -> [String] {
let server = try fetchFromServer()
if !server.isEmpty {
return server
}
return try fetchFromCache()
}
Solution
Step 1: Check async and throws order and usage
The function calls two async throwing functions, so it must be declared async throws with async before throws. Calls to async throwing functions require try await.
Step 2: Analyze each option
func fetchUsernames() async -> [String] {
if let server = await fetchFromServer(), !server.isEmpty {
return server
}
let cache = await fetchFromCache()
return cache
} misses throws and try. async func fetchUsernames() -> [String] {
let server = fetchFromServer()
if !server.isEmpty {
return server
}
return fetchFromCache()
} has wrong syntax placing async before func and missing awaits. func fetchUsernames() throws async -> [String] {
let server = try fetchFromServer()
if !server.isEmpty {
return server
}
return try fetchFromCache()
} swaps throws and async and misses await. Only func fetchUsernames() async throws -> [String] {
let server = try await fetchFromServer()
if !server.isEmpty {
return server
}
return try await fetchFromCache()
} correctly declares and uses try await.