What is cancellation handling in Swift concurrency?
Cancellation handling is the process of stopping a running asynchronous task when it is no longer needed, allowing the program to free resources and avoid unnecessary work.
Click to reveal answer
beginner
How do you check if a Swift Task has been cancelled?
You check if a task has been cancelled by using the property Task.isCancelled inside the task's code.
Click to reveal answer
intermediate
What happens if you throw CancellationError in a Swift async task?
Throwing CancellationError signals that the task was cancelled and allows the task to exit early and clean up resources.
Click to reveal answer
intermediate
Why should you check for cancellation regularly inside long-running async tasks?
Because it lets the task stop work early if cancellation is requested, saving CPU time and improving app responsiveness.
Click to reveal answer
beginner
How do you cancel a running Swift Task?
You call the cancel() method on the Task instance you want to stop.
Click to reveal answer
Which property tells you if a Swift Task has been cancelled?
ATask.isCancelled
BTask.isRunning
CTask.isComplete
DTask.isPaused
✗ Incorrect
Task.isCancelled is true when a cancellation request has been made for the task.
What method do you call to request cancellation of a Swift Task?
Astop()
Bcancel()
Cterminate()
Dend()
✗ Incorrect
The cancel() method requests the task to stop as soon as possible.
What error type is commonly thrown to indicate a cancelled task in Swift concurrency?
AAsyncError
BTaskError
CCancellationError
DStopError
✗ Incorrect
CancellationError is the standard error used to signal task cancellation.
Why is it important to check for cancellation inside a long-running async task?
ATo log task progress
BTo restart the task automatically
CTo increase task priority
DTo free resources and stop unnecessary work
✗ Incorrect
Checking for cancellation lets the task stop early and save resources.
What happens if you ignore cancellation requests in a Swift Task?
AThe task will continue running until completion
BThe task will stop immediately
CThe task will throw an error automatically
DThe task will pause
✗ Incorrect
Ignoring cancellation means the task keeps running and wastes resources.
Explain how to implement cancellation handling in a Swift async task.
Think about how to detect and respond to cancellation requests inside the task.
You got /3 concepts.
Why is cancellation handling important in asynchronous programming?
Consider what happens if tasks run without stopping when they should.
You got /3 concepts.
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
Step 1: Understand cancellation handling concept
Cancellation handling is used to stop tasks that are no longer needed to save resources.
Step 2: Compare options with concept
Only To stop tasks that are no longer needed matches the purpose of stopping unnecessary tasks.
Final Answer:
To stop tasks that are no longer needed -> Option D
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
Step 1: Understand difference between Task.isCancelled and checkCancellation()
Task.checkCancellation() throws if cancelled, so it already handles cancellation detection.
Step 2: Analyze redundancy of Task.isCancelled check
Checking Task.isCancelled before checkCancellation() is redundant because checkCancellation() will throw if cancelled.
Final Answer:
Task.isCancelled check is redundant before checkCancellation() -> Option A
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
Step 1: Analyze cancellation handling in the task
Task.checkCancellation() throws when cancelled, caught by catch block which prints cancellation message.
Step 2: Verify cleanup code execution
Cleanup code runs after catch block, ensuring resources are cleaned up even after cancellation.
Final Answer:
This code correctly cancels the task and runs cleanup after cancellation -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.