Consider the following Swift code using Task to run concurrent work. What will be printed?
import Foundation func fetchData() async -> String { return "Data fetched" } Task { let result = await fetchData() print(result) } print("Task launched")
Remember that Task runs asynchronously and the main thread continues immediately.
The Task runs asynchronously, so print("Task launched") executes first. Then the async function completes and prints Data fetched.
Analyze this Swift code snippet using Task and sleep. What is the output?
import Foundation Task { print("Start") try? await Task.sleep(nanoseconds: 1_000_000_000) print("End") } print("After Task")
The Task runs asynchronously, so the main thread prints before the task finishes.
The main thread prints After Task immediately. The Task prints Start, waits 1 second, then prints End.
Examine this Swift code that launches a Task. It crashes at runtime. What is the cause?
import Foundation var value = 0 Task { value += 1 print(value) } print(value)
Think about shared variable access in concurrent code.
Accessing and modifying value from multiple threads without synchronization causes a data race, which can crash the program.
Choose the correct syntax to launch a detached Task that runs concurrently without inheriting the current context.
Look for the official method name to create a detached task.
The correct method is Task.detached. Other options are invalid syntax or methods.
Consider this Swift code that launches multiple tasks. How many tasks run concurrently and what is printed?
import Foundation for i in 1...3 { Task.detached { print("Task \(i) started") try? await Task.sleep(nanoseconds: 500_000_000) print("Task \(i) finished") } } print("All tasks launched")
Detached tasks run concurrently and the main thread continues immediately.
Three detached tasks run concurrently. The main thread prints "All tasks launched" immediately. Task prints may appear in any order due to concurrency.