0
0
Swiftprogramming~10 mins

Cancellation handling in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Cancellation handling
Start async task
Check for cancellation?
YesStop task early
No
Continue work
Complete task
Return result or error
This flow shows how an async task checks if it was cancelled and stops early if so, otherwise it continues and completes.
Execution Sample
Swift
func fetchData() async throws -> String {
  try Task.checkCancellation()
  // simulate work
  try await Task.sleep(nanoseconds: 1_000_000_000)
  return "Data loaded"
}
This async function checks for cancellation before sleeping 1 second, then returns a string.
Execution Table
StepActionCancellation CheckedResultNext Step
1Start fetchData()NoNo cancellationSleep 1 second
2Sleep for 1 secondNoSleep completesReturn result
3Return "Data loaded"N/ASuccessEnd
4If cancelled before step 1YesThrows CancellationErrorExit early
💡 Task ends either by completing normally or throwing CancellationError if cancelled early.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
isCancelledfalsefalsefalsefalse or true if cancelled
resultnilnilnil"Data loaded" or error
Key Moments - 2 Insights
Why does the function call Task.checkCancellation() at the start?
It immediately checks if the task was cancelled before doing any work, so it can stop early as shown in execution_table row 4.
What happens if the task is cancelled during the sleep?
The sleep is cancellable, so the function throws a CancellationError and exits early, as explained in execution_table row 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 1 if the task is cancelled?
AThe function throws CancellationError and exits early
BThe function continues sleeping
CThe function returns "Data loaded" immediately
DThe function ignores cancellation
💡 Hint
See execution_table row 4 where cancellation is checked at step 1.
According to variable_tracker, what is the value of 'result' after step 2 if not cancelled?
A"Data loaded"
BCancellationError
Cnil
Dfalse
💡 Hint
Result is assigned only after step 3, so after step 2 it is still nil.
If we remove Task.checkCancellation(), what changes in the execution flow?
AThe task sleeps for zero seconds
BThe task never stops early on cancellation
CThe task throws CancellationError immediately
DThe task returns an error immediately
💡 Hint
Without explicit cancellation check, the task continues until it hits a cancellable suspension point.
Concept Snapshot
Cancellation handling in Swift async tasks:
- Use Task.checkCancellation() to detect early cancellation.
- Throw CancellationError to stop work early.
- Cancellable suspension points (like Task.sleep) also throw on cancellation.
- Always check cancellation to avoid wasted work.
- Handle cancellation errors to clean up if needed.
Full Transcript
This visual execution trace shows how Swift async functions handle cancellation. The function fetchData() first calls Task.checkCancellation() to see if the task was cancelled before doing any work. If cancelled, it throws CancellationError and stops early. Otherwise, it continues to sleep for 1 second, which is also cancellable. If cancellation happens during sleep, the function throws and exits early. If no cancellation occurs, it returns the string "Data loaded". The variable tracker shows how the cancellation state and result change step by step. Key moments clarify why checking cancellation early is important and what happens if cancellation occurs during sleep. The quiz tests understanding of cancellation checks, variable states, and effects of removing cancellation checks.