Bird
Raised Fist0
Swiftprogramming~10 mins

Cancellation handling in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Cancellation handling
Start async task
↓
Check for cancellation?
Yes→Stop 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.

Practice

(1/5)
1. What is the main purpose of cancellation handling in Swift concurrency?
easy
A. To create new tasks continuously
B. To speed up all running tasks
C. To restart tasks automatically
D. To stop tasks that are no longer needed

Solution

  1. Step 1: Understand cancellation handling concept

    Cancellation handling is used to stop tasks that are no longer needed to save resources.
  2. Step 2: Compare options with concept

    Only To stop tasks that are no longer needed matches the purpose of stopping unnecessary tasks.
  3. Final Answer:

    To stop tasks that are no longer needed -> Option D
  4. Quick Check:

    Cancellation handling = stop unnecessary tasks [OK]
Hint: Cancellation means stopping tasks early to save resources [OK]
Common Mistakes:
  • Thinking cancellation speeds up tasks
  • Confusing cancellation with restarting tasks
  • Assuming cancellation creates new tasks
2. Which of the following is the correct way to check for cancellation inside a Swift async task?
easy
A. if Task.cancelled() { return }
B. if Task.isCancelled { return }
C. if Task.checkCancel() { return }
D. if Task.isCancel { return }

Solution

  1. Step 1: Recall correct API for cancellation check

    The correct property to check cancellation is Task.isCancelled.
  2. Step 2: Verify syntax correctness

    if Task.isCancelled { return } uses Task.isCancelled correctly; others use invalid method or property names.
  3. Final Answer:

    if Task.isCancelled { return } -> Option B
  4. Quick Check:

    Use Task.isCancelled to check cancellation [OK]
Hint: Remember: Task.isCancelled is a property, not a method [OK]
Common Mistakes:
  • Using incorrect method names like cancelled()
  • Confusing property names with similar words
  • Missing capitalization or spelling errors
3. What will be the output of the following Swift code snippet?
Task {
    for i in 1...3 {
        try Task.checkCancellation()
        print("Running step \(i)")
        if i == 2 {
            Task.current.cancel()
        }
    }
}
medium
A. Running step 1 Running step 2
B. Running step 1 Running step 2 Running step 3
C. Running step 1
D. No output due to immediate cancellation

Solution

  1. Step 1: Understand Task.checkCancellation() behavior

    Task.checkCancellation() throws if the task is cancelled, stopping further execution.
  2. Step 2: Analyze loop and cancellation timing

    Cancellation happens when i == 2, so steps 1 and 2 print, but step 3 is skipped due to cancellation.
  3. Final Answer:

    Running step 1\nRunning step 2 -> Option A
  4. Quick Check:

    Cancellation after step 2 stops step 3 [OK]
Hint: Cancellation stops loop after current iteration [OK]
Common Mistakes:
  • Assuming all steps run despite cancellation
  • Ignoring that checkCancellation throws on cancel
  • Thinking cancellation happens before step 2
4. Identify the error in this Swift async task cancellation handling code:
Task {
    if Task.isCancelled {
        print("Cancelled")
    }
    try Task.checkCancellation()
    print("Running")
}
medium
A. Task.isCancelled check is redundant before checkCancellation()
B. Missing try keyword before Task.checkCancellation()
C. No error; code handles cancellation correctly
D. Task.isCancelled should be checked after checkCancellation()

Solution

  1. Step 1: Understand difference between Task.isCancelled and checkCancellation()

    Task.checkCancellation() throws if cancelled, so it already handles cancellation detection.
  2. Step 2: Analyze redundancy of Task.isCancelled check

    Checking Task.isCancelled before checkCancellation() is redundant because checkCancellation() will throw if cancelled.
  3. Final Answer:

    Task.isCancelled check is redundant before checkCancellation() -> Option A
  4. Quick Check:

    checkCancellation() alone suffices to detect cancellation [OK]
Hint: Use checkCancellation() to handle cancellation, no need for isCancelled first [OK]
Common Mistakes:
  • Thinking isCancelled must come before checkCancellation()
  • Missing try keyword (actually present here)
  • Assuming no error when redundancy exists
5. You want to cancel a long-running Swift async task when a user taps a cancel button. Which approach correctly handles cancellation and cleans up resources?
func performTask() async {
    let task = Task {
        do {
            for i in 1...5 {
                try Task.checkCancellation()
                print("Processing \(i)")
                try await Task.sleep(nanoseconds: 1_000_000_000)
            }
        } catch {
            print("Task was cancelled")
        }
        print("Cleanup done")
    }
    // User taps cancel button
    task.cancel()
}
hard
A. Task.cancel() should be called inside the task, not outside
B. Cleanup code will not run after cancellation
C. This code correctly cancels the task and runs cleanup after cancellation
D. Task.checkCancellation() does not throw, so cancellation is ignored

Solution

  1. Step 1: Analyze cancellation handling in the task

    Task.checkCancellation() throws when cancelled, caught by catch block which prints cancellation message.
  2. Step 2: Verify cleanup code execution

    Cleanup code runs after catch block, ensuring resources are cleaned up even after cancellation.
  3. Final Answer:

    This code correctly cancels the task and runs cleanup after cancellation -> Option C
  4. Quick Check:

    Cancellation triggers catch and cleanup runs [OK]
Hint: Use try/catch with checkCancellation() to handle cancel and cleanup [OK]
Common Mistakes:
  • Assuming cleanup won't run after cancellation
  • Calling cancel() inside the task incorrectly
  • Believing checkCancellation() does not throw
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard