0
0
Swiftprogramming~30 mins

Task for launching concurrent work in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Task for launching concurrent work
📖 Scenario: You are building a simple Swift program that runs two tasks at the same time to save time. This is like asking two friends to do two jobs together instead of waiting for one to finish before starting the other.
🎯 Goal: Learn how to use Task in Swift to launch concurrent work and print results when both tasks finish.
📋 What You'll Learn
Create two separate tasks using Task
Each task should print a message after a short delay
Use await to wait for both tasks to finish
Print a final message after both tasks complete
💡 Why This Matters
🌍 Real World
Running multiple tasks at the same time helps apps stay fast and responsive, like loading images while fetching data.
💼 Career
Understanding concurrency with Swift's Task API is important for building efficient iOS and macOS apps that handle multiple operations smoothly.
Progress0 / 4 steps
1
Create two async functions
Write two async functions called taskOne() and taskTwo(). Each function should wait for 1 second using Task.sleep and then print "Task One done" or "Task Two done" respectively.
Swift
Need a hint?

Use try? await Task.sleep(nanoseconds: 1_000_000_000) to wait 1 second inside each async function.

2
Launch tasks concurrently
Create two variables task1 and task2 using Task to run taskOne() and taskTwo() concurrently.
Swift
Need a hint?

Use let task1 = Task { await taskOne() } and similarly for task2.

3
Wait for both tasks to finish
Use await on task1.value and task2.value to wait for both tasks to complete.
Swift
Need a hint?

Use await task1.value and await task2.value inside a Task to wait for both.

4
Print final message after tasks complete
After awaiting both tasks, print "Both tasks completed" inside the same Task.
Swift
Need a hint?

After waiting for both tasks, add print("Both tasks completed").