skip to content

A Swift async wrapper around a location SDK sometimes hangs forever and sometimes crashes with SWIFT TASK CONTINUATION MISUSE; what causes each, and how do you fix them?

level: seniorimportance: should knowfreq 45%

answer

  1. exactly once, on every path
  2. never resumed: logged and stuck
  3. resumed twice: trap
  4. the leak check fires on release
  5. the unsafe variant checks nothing

basics

~20 s

A continuation must be resumed exactly once. A path that never resumes leaves the caller suspended forever, and CheckedContinuation only logs that leak when its last reference is released; a second resume traps. Resume on every path, then drop the continuation.

solid answer

~50 s

Both are breaches of the rule that a continuation is resumed **exactly once on every path**. The hang is a path that never resumes: an early `return`, an SDK that silently drops its callback when access is denied, or a delegate continuation overwritten by a second caller. The awaiting task stays suspended for good. `CheckedContinuation` notices only when its last reference is released, and then *logs* `SWIFT TASK CONTINUATION MISUSE: … leaked its continuation without resuming it` without crashing; if the SDK keeps the callback forever, nothing is logged. The crash is a second resume, typically a callback that fires once per location update: `CheckedContinuation` traps with `… tried to resume its continuation more than once`. Fix by resuming on every path, keeping the continuation in an optional and setting it to `nil` after the first resume, rejecting overlapping calls, and moving multi-value APIs to an asynchronous stream. `withUnsafeContinuation` checks none of this.

code

swift · 21 lines
swift
struct Coordinate: Sendable { let latitude: Double; let longitude: Double }

final class LegacyLocationSDK: Sendable {
    let authorized: Bool
    init(authorized: Bool) { self.authorized = authorized }

    // Calls back once when authorized; otherwise drops the callback.
    func requestLocation(completion: @escaping @Sendable (Coordinate) -> Void) {
        guard authorized else { return }
        completion(Coordinate(latitude: 59.91, longitude: 10.75))
    }
}

// Bug: when the user has denied access, nothing ever resumes the continuation.
func currentLocation(using sdk: LegacyLocationSDK) async -> Coordinate {
    await withCheckedContinuation { continuation in
        sdk.requestLocation { coordinate in
            continuation.resume(returning: coordinate)
        }
    }
}

go deeper

for a junior

Recall that a continuation must be resumed exactly once, and that missing or doubling the resume causes a hang or a crash.

for a middle

Explain what CheckedContinuation reports for each mistake: a logged leak on release and a fatal error on a second resume.

for a senior

Diagnose hangs and traps in continuation wrappers, including silent leaks from retained callbacks, and apply store-resume-clear in delegate wrappers.

for a principal

Set the team rule on checked versus unsafe continuations and on when a callback API should become a stream instead of a continuation.

## The contract The standard library's documentation for `CheckedContinuation` states the rule: you must call a resume method **exactly once on every execution path**. Resuming more than once is undefined behaviour; never resuming leaves the task suspended indefinitely and leaks whatever it holds. `CheckedContinuation`, the type you get from `withCheckedContinuation` and `withCheckedThrowingContinuation`, adds run-time checks for both mistakes, and Swift Evolution's continuation proposal notes that they run regardless of optimisation level, so release builds keep them. ## The hang: a path that never resumes The awaiting task cannot time out or give up on its own. Common causes: - an early `return` or `guard` inside the continuation closure that skips the resume; - an SDK that never calls back on some path, such as when location access is denied; - a completion handler that handles a value and an error but forgets the case where both are `nil`; - a delegate wrapper that stores the continuation in a property, so a second call overwrites the first, which is then never resumed. `CheckedContinuation` detects a leak with a `deinit` on an internal object: when the last reference goes away unresumed, it **logs** `SWIFT TASK CONTINUATION MISUSE: currentLocation(using:) leaked its continuation without resuming it. This may cause tasks waiting on it to remain suspended forever.` The name comes from the `function:` parameter, which defaults to `#function`. Two limits matter in production: 1. It is a log line, not a crash, so the app keeps running with a stuck task. 2. It fires only on release. If the SDK keeps the completion handler forever, the continuation is never released, and the hang is silent. Cancelling the stuck task does not help: cancellation does not resume a continuation (wiring that up is covered in the lesson on cancellation). ## The crash: a second resume `resume(returning:)` and `resume(throwing:)` take the underlying continuation atomically. The second call finds it gone and calls `fatalError`, with a message like `SWIFT TASK CONTINUATION MISUSE: twice() tried to resume its continuation more than once, returning 2!`. Typical causes: - a callback that fires once per update, such as a location SDK delivering a rough fix and then a precise one; - a callback that reports an error and then a value, or retries and reports again; - resuming in the closure itself and again in the callback. ## Fixing both 1. **Resume on every path.** Read each branch of the handler, including `guard` exits and the both-`nil` case, and make sure exactly one resume runs. 2. **Store, resume, clear.** In a delegate wrapper keep `CheckedContinuation?` in a property, resume it with optional chaining, and set it to `nil` at once, so later callbacks find nothing to resume. 3. **Reject overlap.** If a continuation is already pending, resume the new one with an error instead of overwriting the old one. 4. **Use the right shape.** An API that delivers many values belongs in an asynchronous stream (covered in the lesson on async sequences), not a continuation. 5. **Keep the type isolated.** Put the stored continuation on an actor or the main actor, so the check-and-clear cannot race with another callback. ## Checked versus unsafe | | `withCheckedContinuation` | `withUnsafeContinuation` | |---|---|---| | Resumed twice | traps with a misuse message | undefined behaviour | | Never resumed | logs a misuse message on release | nothing reported | | Run-time cost | a small object and an atomic exchange | no extra checks | | Strict memory safety mode | no diagnostic | the call is flagged as unsafe | The documentation notes that the two share an interface, so one can replace the other, and that verifying the rules during development is important; keep the checked type unless a measured hot path needs the unsafe one. In Swift 6.4, `withUnsafeContinuation` is declared `@unsafe`; with the opt-in `-strict-memory-safety` flag (strict memory safety mode, added in **Swift 6.2**) the compiler warns `expression uses unsafe constructs but is not marked with 'unsafe'`. Most code should simply keep the checked variant. ## Catching it before users do - Search logs for `SWIFT TASK CONTINUATION MISUSE`: the function name in the message points at the wrapper. - Write tests with a fake SDK that never calls back, calls back twice, and calls back with neither a value nor an error. - Review each continuation closure for `return` and `guard` exits that skip a resume.

  • Why might a leaked continuation produce no log message at all?
    `CheckedContinuation` reports a leak from a `deinit`, so the message appears only when its last reference is released. If the SDK stores the completion handler forever, or your own object keeps the continuation in a property that is never cleared, it is never released: the task hangs and nothing is logged. Look for suspended tasks, not just log lines.
  • Does cancelling the task that is awaiting a continuation make it return?
    No. Cancellation is a flag; a task suspended on a continuation stays suspended until something calls resume. To make cancellation end the wait, you resume the continuation, usually with `CancellationError()`, from a cancellation handler, and ideally stop the SDK request too. That wiring is covered in the lesson on cancellation.
  • When is `withUnsafeContinuation` worth using?
    Rarely: only on a hot path where profiling shows the checked type's small allocation and atomic exchange matter. It has the same interface, so you can develop with the checked version and swap later. You give up both checks: a double resume becomes undefined behaviour and a leak goes unreported.

  • CheckedContinuation crashes the app when a continuation is never resumed
  • Resuming a continuation a second time is silently ignored
  • Every leaked continuation is reported in the log
  • Release builds strip the checked continuation's run-time checks
  • withUnsafeContinuation still traps on a double resume, only faster
  • Storing the continuation in a property makes a double resume impossible

Assumes Swift 6.4; withUnsafeContinuation is marked @unsafe, which the opt-in strict memory safety mode added in Swift 6.2 diagnoses.