Await for calling async functions in Swift - Time & Space Complexity
When we use await to call async functions, we want to know how the waiting affects the program's speed.
We ask: How does the total time grow when we wait for multiple async calls?
Analyze the time complexity of the following code snippet.
func fetchData(id: Int) async -> String {
// Simulate network delay
try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
return "Data \(id)"
}
func loadAllData(ids: [Int]) async -> [String] {
var results = [String]()
for id in ids {
let data = await fetchData(id: id)
results.append(data)
}
return results
}
This code fetches data for each id one by one, waiting for each async call to finish before starting the next.
- Primary operation: The
forloop callsfetchDatafor each id. - How many times: Once for each element in the
idsarray.
Each async call waits about 1 second before returning. Since calls happen one after another, total time adds up.
| Input Size (n) | Approx. Operations (seconds) |
|---|---|
| 10 | ~10 seconds |
| 100 | ~100 seconds |
| 1000 | ~1000 seconds |
Pattern observation: Total time grows directly with the number of calls, because each waits for the previous to finish.
Time Complexity: O(n)
This means the total waiting time grows linearly with the number of async calls.
[X] Wrong: "Using await inside a loop runs all async calls at the same time, so total time stays the same no matter how many calls."
[OK] Correct: Await inside a loop waits for each call to finish before starting the next, so calls run one after another, increasing total time.
Understanding how awaiting async calls affects time helps you write efficient code and explain your reasoning clearly in interviews.
What if we started all async calls without awaiting inside the loop, then awaited all results together? How would the time complexity change?
Practice
await keyword do when calling an async function in Swift?Solution
Step 1: Understand the role of
Theawaitawaitkeyword tells Swift to pause the current code execution until the async function completes.Step 2: Recognize the effect on program flow
This means the program waits for the async task to finish and then continues with the result.Final Answer:
It pauses the current code until the async function finishes and returns a result. -> Option BQuick Check:
awaitpauses code = A [OK]
- Thinking await makes code run faster
- Believing await runs code in background without waiting
- Confusing await with automatic sync conversion
fetchData() inside another async function in Swift?Solution
Step 1: Recall async function call syntax
When calling an async function, you must useawaitbefore the function call to wait for its result.Step 2: Check the correct placement of
The correct syntax isawaitlet result = await fetchData(). Theawaitkeyword comes before the function call.Final Answer:
let result = await fetchData() -> Option DQuick Check:
Useawaitbefore async call = D [OK]
- Omitting await before the async call
- Placing await after the assignment
- Using async keyword instead of await
func fetchNumber() async -> Int {
return 42
}
func printNumber() async {
let number = await fetchNumber()
print(number)
}
Task {
await printNumber()
}Solution
Step 1: Understand async function behavior
The functionfetchNumber()returns 42 asynchronously. Usingawaitwaits for this value.Step 2: Trace the print statement
TheprintNumber()function awaitsfetchNumber()and prints the returned integer 42.Final Answer:
42 -> Option CQuick Check:
Await returns 42 printed = A [OK]
- Expecting Optional(42) instead of 42
- Thinking code won't run without main async
- Missing await causing compile error
func getData() async -> String {
return "Hello"
}
func showData() {
let message = await getData()
print(message)
}Solution
Step 1: Check where await is used
Theawaitkeyword is used insideshowData(), but this function is not marked async.Step 2: Understand async function rules
In Swift, you can only useawaitinside an async function or a Task closure. SoshowData()must be declared async.Final Answer:
showData() must be marked async to use await inside it -> Option AQuick Check:
Await requires async function = B [OK]
- Forgetting to mark function async when using await
- Thinking await can be used in normal functions
- Confusing async function declaration with await usage
fetchUser() and fetchPosts(userId:). How do you correctly wait for both results in sequence inside an async function?Solution
Step 1: Await the first async call to get user
You must useawaitbeforefetchUser()to get the user data before using it.Step 2: Await the second async call using user.id
After getting the user, callfetchPosts(userId: user.id)withawaitto get posts.Final Answer:
let user = await fetchUser() let posts = await fetchPosts(userId: user.id) -> Option AQuick Check:
Await each async call in order = C [OK]
- Not awaiting the second async call
- Trying to await variable declarations incorrectly
- Using await inside function arguments wrongly
Ready to prove it?
Pass the test and this pattern moves unknown
