Home / Swift concurrency cancellation interview question

Swift concurrency

Swift concurrency cancellation interview question

Cancellation is a favorite senior question because it separates people who read about concurrency from people who shipped it.

How cancellation works

Swift cancellation is cooperative: cancelling a task sets a flag, it does not forcibly stop the work. Your code must observe it, either by calling Task.checkCancellation, which throws CancellationError, or by checking Task.isCancelled and returning early. Structured child tasks are cancelled automatically when their parent is cancelled or its scope exits.

Where it matters in practice

The classic example is search-as-you-type: when new input arrives you cancel the in-flight request so a stale response cannot overwrite fresh results. Explain that long-running or looping work should check for cancellation periodically, and that ignoring cancellation wastes resources and causes race-like UI bugs. That production framing is the signal.

Go deeper than a summary

Share Your Screen works topics like this through in full: 75 solved Swift problems with tests, 9 real case studies, and 7 annotated mock interviews, so you rehearse the live round instead of just reading about it.

Get the book

Frequently asked

Is Swift task cancellation automatic?

No, it is cooperative. Cancelling sets a flag; your code must check Task.isCancelled or call checkCancellation and stop. Structured child tasks are cancelled with their parent.

How do you cancel a stale network request?

Hold the Task, and when new input arrives call cancel on the old one. The awaited work should observe cancellation and throw or return before applying a stale result.