Task for launching concurrent work in Swift - Time & Space Complexity
When we launch work to run at the same time using tasks, it's important to see how the time needed changes as we add more tasks.
We want to know how the total work grows when we start many tasks concurrently.
Analyze the time complexity of the following code snippet.
func launchTasks(count: Int) async {
for i in 1...count {
Task {
print("Task \(i) started")
// Simulate some work
try? await Task.sleep(nanoseconds: 1_000_000)
print("Task \(i) finished")
}
}
}
This code launches a number of tasks concurrently, each doing a small amount of work.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that creates and starts each Task.
- How many times: Exactly once for each task, so count times.
Each new task adds one more unit of work to start, but tasks run at the same time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks started quickly |
| 100 | 100 tasks started quickly |
| 1000 | 1000 tasks started quickly |
Pattern observation: The number of task launches grows directly with input size, but tasks run concurrently, so total time does not grow much with more tasks.
Time Complexity: O(n)
This means the work to start tasks grows linearly with the number of tasks, but the tasks themselves run at the same time.
[X] Wrong: "Starting many tasks means the total time will be n times longer."
[OK] Correct: Tasks run concurrently, so starting more tasks adds work to launch them, but they mostly run at the same time, not one after another.
Understanding how launching concurrent tasks scales helps you explain how programs handle many jobs at once, a useful skill in real projects and interviews.
"What if each task waited for the previous one to finish before starting? How would the time complexity change?"
Practice
What does Task { } do in Swift concurrency?
Solution
Step 1: Understand the purpose of Task
Task { }is used to start work that runs at the same time as other code, without blocking.Step 2: Compare options
Only Starts a new piece of work that runs concurrently with other code correctly describes this concurrent behavior. Options A, B, and D are incorrect because they describe blocking, synchronous, or stopping behavior, whichTaskdoes not do.Final Answer:
Starts a new piece of work that runs concurrently with other code -> Option BQuick Check:
Task starts concurrent work = C [OK]
- Thinking Task blocks the main thread
- Confusing Task with synchronous functions
- Believing Task stops other tasks
Which of the following is the correct syntax to start a new concurrent task in Swift?
?Solution
Step 1: Recall correct Task syntax
The correct way to start a concurrent task isTask { }with a closure inside. Usingawaitis needed if calling async functions.Step 2: Check each option
Task { await fetchData() } uses correct capitalization and syntax. Options A, C, and D use incorrect keywords or syntax.Final Answer:
Task { await fetchData() } -> Option DQuick Check:
Correct Task syntax = B [OK]
- Using lowercase 'task' instead of 'Task'
- Adding 'start' method which doesn't exist
- Adding 'async' keyword before Task incorrectly
What will be printed by this Swift code?
Task {
print("Start")
await Task.sleep(1_000_000_000) // 1 second
print("End")
}
print("Outside")Solution
Step 1: Understand Task concurrency
TheTask { }runs concurrently, so "Start" prints immediately when the task begins.Step 2: Trace print order
Within the Task, "Start" prints first, then the task sleeps for 1 second, then prints "End". Meanwhile, the main thread continues and prints "Outside" immediately after starting the Task.Step 3: Determine exact order
Because the Task closure starts immediately and prints "Start" before sleeping, "Start" prints before "Outside". Then "Outside" prints, and after 1 second delay, "End" prints.Final Answer:
Start\nOutside\nEnd -> Option AQuick Check:
Task prints Start immediately, main prints Outside, then Task prints End = D [OK]
- Assuming 'Outside' prints before 'Start'
- Ignoring that Task closure starts immediately
- Thinking Task blocks main thread
Identify the error in this Swift code that tries to launch a concurrent task:
Task {
let result = fetchData()
print(result)
}Assuming fetchData() is an async function.
Solution
Step 1: Check async function call
SincefetchData()is async, it must be called withawaitinside an async context like Task.Step 2: Identify missing await
The code missesawaitbeforefetchData(), causing a compile error.Final Answer:
MissingawaitbeforefetchData()-> Option AQuick Check:
Async calls need await = A [OK]
- Forgetting await on async calls
- Thinking Task disallows async calls
- Believing print can't be used inside Task
You want to fetch user data and update the UI without blocking the main thread. Which is the best way to launch this concurrent work?
func updateUI(with data: String) {
print("UI updated with \(data)")
}
func fetchUserData() async -> String {
// Simulate network delay
await Task.sleep(2_000_000_000)
return "User123"
}
// What code should you write here?Solution
Step 1: Understand async fetch and UI update
Fetching user data is async and takes time. To avoid blocking, useTask { }to run it concurrently.Step 2: Use await and update UI inside Task
Inside the Task, await the async fetch, then update the UI with the result. This keeps UI responsive.Final Answer:
Task { let data = await fetchUserData() updateUI(with: data) } -> Option CQuick Check:
Await async fetch inside Task, then update UI = A [OK]
- Calling async function without await
- Updating UI outside Task causing blocking
- Not using Task for concurrency
Ready to prove it?
Pass the test and this pattern moves unknown
