0
0
Swiftprogramming~30 mins

Cancellation handling in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Cancellation Handling in Swift Async Tasks
📖 Scenario: Imagine you are building a simple Swift app that fetches user data from the internet. Sometimes, the user might want to cancel the fetch if it takes too long or they change their mind.
🎯 Goal: You will create a Swift async function that simulates fetching data, add a cancellation check, and then handle the cancellation properly.
📋 What You'll Learn
Create an async function called fetchUserData() that simulates a delay
Create a Task to run fetchUserData()
Add a cancellation check inside fetchUserData() using Task.isCancelled
Cancel the Task before it finishes
Print messages to show if the task completed or was cancelled
💡 Why This Matters
🌍 Real World
Handling cancellation is important in apps where users may want to stop long-running tasks like downloads or data fetching to save time and resources.
💼 Career
Understanding cancellation in async tasks is essential for Swift developers building responsive and user-friendly iOS or macOS apps.
Progress0 / 4 steps
1
Create the async function to simulate data fetching
Write an async function called fetchUserData() that waits for 5 seconds using Task.sleep and then prints "User data fetched".
Swift
Need a hint?

Use Task.sleep(nanoseconds: 5_000_000_000) to wait 5 seconds inside the async function.

2
Create a Task to run the async function
Create a Task called userTask that runs fetchUserData() asynchronously.
Swift
Need a hint?

Use let userTask = Task { await fetchUserData() } to start the async task.

3
Add cancellation check inside the async function
Modify fetchUserData() to check Task.isCancelled after sleeping. If cancelled, print "Fetch cancelled" and return early.
Swift
Need a hint?

Use if Task.isCancelled { print("Fetch cancelled"); return } after the sleep.

4
Cancel the task and print the result
Call userTask.cancel() immediately after creating the task. Then wait 6 seconds using Task.sleep to allow the task to finish or cancel.
Swift
Need a hint?

Use userTask.cancel() to cancel and then Task.sleep(nanoseconds: 6_000_000_000) to wait.