Taskawait to wait for both tasks to finishTaskawait to wait for both tasks to finishtaskOne() and taskTwo(). Each function should wait for 1 second using Task.sleep and then print "Task One done" or "Task Two done" respectively.Use try? await Task.sleep(nanoseconds: 1_000_000_000) to wait 1 second inside each async function.
task1 and task2 using Task to run taskOne() and taskTwo() concurrently.Use let task1 = Task { await taskOne() } and similarly for task2.
await on task1.value and task2.value to wait for both tasks to complete.Use await task1.value and await task2.value inside a Task to wait for both.
"Both tasks completed" inside the same Task.After waiting for both tasks, add print("Both tasks completed").
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