Concept Flow - Task for launching concurrent work
Start
Create Task
Task Runs Concurrently
Task Completes
Main Code Continues
This flow shows how a Task is created to run code concurrently, allowing the main program to continue without waiting.
Task {
print("Hello from Task")
}
print("Hello from Main")| Step | Action | Code Executed | Output | Notes |
|---|---|---|---|---|
| 1 | Create Task | Task { print("Hello from Task") } | Task is created but runs concurrently | |
| 2 | Main code runs | print("Hello from Main") | Hello from Main | Main thread prints immediately |
| 3 | Task runs | print("Hello from Task") | Hello from Task | Task prints concurrently, may appear before or after main output |
| 4 | End | Program ends after both prints |
| Variable | Start | After Task Created | After Main Print | After Task Print | Final |
|---|---|---|---|---|---|
| Task | nil | Task instance created | Task running concurrently | Task completed | nil |
Task { ... } launches concurrent work in Swift.
The main code continues immediately without waiting.
Task runs asynchronously and can print or do work.
Outputs may appear in any order.
Use Task to run code concurrently simply.What does Task { } do in Swift concurrency?
Task { } is used to start work that runs at the same time as other code, without blocking.Task does not do.Which of the following is the correct syntax to start a new concurrent task in Swift?
?Task { } with a closure inside. Using await is needed if calling async functions.What will be printed by this Swift code?
Task {
print("Start")
await Task.sleep(1_000_000_000) // 1 second
print("End")
}
print("Outside")Task { } runs concurrently, so "Start" prints immediately when the task begins.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.
fetchData() is async, it must be called with await inside an async context like Task.await before fetchData(), causing a compile error.await before fetchData() -> Option AYou 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?Task { } to run it concurrently.Pass the test and this pattern moves unknown