DEV Community

Cover image for Continuations in Practice: What SE-0564 Split Continuations Changes
Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on Edited on

Continuations in Practice: What SE-0564 Split Continuations Changes

Most iOS codebases still have callback APIs at their edges: an analytics SDK, a Bluetooth stack, a payment library, an old networking layer nobody wants to rewrite. Continuations are how those APIs become async functions. The conversion looks trivial, but it is the place I have seen the most subtle concurrency bugs: tasks that hang forever, crashes that only happen under load, and cancellation that silently does nothing.

This article covers how continuations behave in real code, the three classic bugs (double resume, missing resume, ignored cancellation) and how to fix each one with today's APIs. It then covers what SE-0564: Split continuations changes.

How the examples were checked:

  • Today's APIs (CheckedContinuation, withTaskCancellationHandler, Mutex): every example was compiled and tested with Swift 6.2.4 in Swift 6 language mode (source on GitHub). The test suite includes 400 runs that deliberately race a timeout against completion and cancellation against completion. The runtime messages quoted below can be reproduced with the package's MisuseDemo target (swift run MisuseDemo double / leak).
  • New APIs from SE-0528 (Continuation) and SE-0564 (ContinuationWaiter, resumeSynchronously): these need a newer toolchain and runtime. Those examples follow the signatures in the proposals and are marked as such.

1. Why continuations still matter

Here is a typical SDK method:

func fetchData(completion: @escaping @Sendable (Result<Data, SDKError>) -> Void) -> SDKRequest
Enter fullscreen mode Exit fullscreen mode

You can't change it, but the rest of your app is async/await. You want call sites to look like this:

let data = try await client.data()
Enter fullscreen mode Exit fullscreen mode

A continuation is the bridge. It suspends the calling task and gives you a handle that the callback uses to resume it:

extension LegacyClient {
    func data() async throws -> Data {
        try await withCheckedThrowingContinuation { continuation in
            fetchData { result in
                continuation.resume(with: result)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

That's the whole pattern, and for a well-behaved SDK it's correct. The trouble is the rule hidden inside it: the continuation must be resumed exactly once, on every path. The compiler can't check that for CheckedContinuation or UnsafeContinuation. Most continuation bugs come down to breaking that rule.

2. What happens under the hood

The lifecycle of one continuation:

Lifecycle of one continuation: the async task creates the continuation, hands it to the callback API and suspends; the callback fires on any thread and resumes exactly once; the task then continues on its own executor

A few details that matter in practice:

  • The body of withChecked(Throwing)Continuation runs synchronously in the calling task, before the task suspends. That's where you register the callback.
  • The callback can fire before the body returns, or even synchronously inside fetchData. That's allowed: if the continuation is resumed before the task suspends, the task just doesn't wait.
  • Resuming doesn't run your code right away on the callback's thread. resume schedules the suspended task back onto the executor it needs, such as the main actor, an actor, or the global concurrent executor. The code after await runs later, on that executor. Don't assume the callback thread and the resumed code share a thread or happen in a particular order.
  • A continuation is not a Task. It doesn't run anything itself. It's a one-shot handle to resume an existing task that is suspended at one await.

3. The double resume problem

The most common real-world version is a timeout. The request completes, but a timer you added also fires, and both try to finish the operation:

// ❌ Broken: both paths resume the same continuation
func data(timeout: Duration) async throws -> Data {
    try await withCheckedThrowingContinuation { continuation in
        let request = fetchData { result in
            continuation.resume(with: result)               // path 1
        }
        Task {
            try? await Task.sleep(for: timeout)
            request.cancel()
            continuation.resume(throwing: SDKError.timedOut) // path 2
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

When the request is slower than the timeout, path 2 resumes first. Then the SDK reports .cancelled through path 1 and resumes a second time. Here is what each continuation type does:

Double resume
CheckedContinuation Traps (crash)
UnsafeContinuation Undefined behavior: anything from "seems fine" to memory corruption
SE-0528 Continuation Won't compile when the second resume is visible to the compiler

The real message from a checked continuation, captured on Swift 6.2.4:

Fatal error: SWIFT TASK CONTINUATION MISUSE: twice() tried to resume its continuation more than once, returning 2!
Enter fullscreen mode Exit fullscreen mode

That crash is the checked continuation doing its job. UnsafeContinuation doesn't make this code safe. It only removes the check. Use it only when you can show that exactly one resume happens, and you've measured that the checked version's cost matters.

Why a boolean flag isn't enough

A common first fix:

var resumed = false
// ... in both paths:
if !resumed { resumed = true; continuation.resume(...) }
Enter fullscreen mode Exit fullscreen mode

The completion handler and the timer run on different threads, so both can read false before either writes true. That's a data race, and Swift 6 rejects the captured mutable variable for exactly this reason. The check and the update have to be one atomic step.

A correct fix: take the continuation under a lock

Store the continuation in a Mutex and have each path take it out. The first caller gets it, and later callers get nil:

import Synchronization

/// Hands out a checked continuation exactly once. The first caller wins.
final class ResumeOnce<T: Sendable, E: Error>: Sendable {
    private let state: Mutex<CheckedContinuation<T, E>?>

    init(_ continuation: CheckedContinuation<T, E>) {
        state = Mutex(continuation)
    }

    @discardableResult
    func resume(with result: sending Result<T, E>) -> Bool {
        // Take it under the lock, resume it outside the lock.
        guard let continuation = state.withLock({ $0.take() }) else { return false }
        continuation.resume(with: result)
        return true
    }
}

func data(timeout: Duration) async throws -> Data {
    try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Data, any Error>) in
        let once = ResumeOnce(continuation)
        let timer = TimerHandle()
        let request = fetchData { result in
            if once.resume(with: result.mapError { $0 as any Error }) {
                timer.cancel() // we won the race, so stop the timer
            }
        }
        timer.set(Task {
            do {
                try await Task.sleep(for: timeout)
            } catch {
                return // cancelled: the completion already won
            }
            if once.resume(with: .failure(SDKError.timedOut)) {
                request.cancel() // we won the race, so stop the SDK work
            }
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

TimerHandle is a small Mutex-backed holder for the timer task. If the completion calls cancel() before the task has been stored, set(_:) cancels it right away (full code).

Three details matter here:

  • Resume outside the lock. Resuming schedules other work, so don't do it while holding a lock other threads may be waiting on.
  • The winner does the cleanup. Only the path that actually resumed cancels the other one: the timer cancels the request, and the completion cancels the timer.
  • Don't leave the loser running. Without timer.cancel(), every fast request still leaves a task sleeping for the full timeout, holding once and request alive. Under load, that adds up. A task group racing the fetch against Task.sleep is a structured alternative.

Mutex needs iOS 18 / macOS 15. On older deployment targets, OSAllocatedUnfairLock (iOS 16+) works the same way. An actor works too, as long as the callback can afford to hop into it.

4. The missing resume problem

The opposite bug is quieter: the continuation is never resumed. Common causes:

  • An error path returns early and forgets to resume:
  // ❌ Broken: the guard path never resumes
  try await withCheckedThrowingContinuation { continuation in
      guard let url = makeURL() else { return }
      load(url) { continuation.resume(with: $0) }
  }
Enter fullscreen mode Exit fullscreen mode
  • The SDK drops the completion when cancelled, instead of calling it with an error.
  • A delegate callback never arrives, for example a Bluetooth peripheral that disconnects mid-operation.
  • The object holding the continuation is deallocated without resuming it.

The task stays suspended forever. It isn't cancelled and it isn't an error: everything it captured stays alive, and the caller's await never returns. async/await doesn't fix this for you.

How each continuation type reacts:

Missing resume
CheckedContinuation Logs a warning when the continuation is destroyed without being resumed. The task still hangs.
UnsafeContinuation Silent hang
SE-0528 Continuation Traps when it's dropped without being resumed

The checked warning, captured on Swift 6.2.4:

SWIFT TASK CONTINUATION MISUSE: leaky() leaked its continuation without resuming it. This may cause tasks waiting on it to remain suspended forever.
Enter fullscreen mode Exit fullscreen mode

Watch for this message in your logs. It's often the only clue to a "screen stuck on a spinner" bug report.

The fix is discipline: every path ends in exactly one resume.

// ✅ Every path resumes
try await withCheckedThrowingContinuation { continuation in
    guard let url = makeURL() else {
        continuation.resume(throwing: SDKError.server(-1))
        return
    }
    load(url) { continuation.resume(with: $0) }
}
Enter fullscreen mode Exit fullscreen mode

For SDKs that can drop callbacks, add your own guaranteed ending, such as a timeout or a cancellation path. Use the ResumeOnce pattern above so that ending can't collide with a late callback.

5. Cancellation is not automatic

Cancelling a Swift Task only sets a flag on it. It doesn't stop the SDK request, and it doesn't resume your continuation. If the user leaves the screen, a plain continuation bridge keeps the request running and the task suspended until the SDK finishes on its own.

The tool for this is withTaskCancellationHandler:

// ❌ Looks right, but has two races
func data() async throws -> Data {
    var request: SDKRequest?            // also a data race in Swift 6
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            request = fetchData { continuation.resume(with: $0) }
        }
    } onCancel: {
        request?.cancel()
    }
}
Enter fullscreen mode Exit fullscreen mode

The problems:

  1. onCancel can run before the request exists. If the task is already cancelled, onCancel runs immediately, before the continuation body. It can also run concurrently with the body on another thread. Either way, it may find request == nil and do nothing, so the request runs anyway.
  2. Cancellation and completion race. The SDK may finish at the same moment you cancel, and both paths must still produce exactly one resume.

A correct version needs shared state that the body and the handler can both see, with each change made under a lock:

final class CancellableFetch: Sendable {
    private enum State {
        case idle
        case cancelledBeforeStart
        case waiting(CheckedContinuation<Data, any Error>, SDKRequest?, cancelRequested: Bool)
        case finished
    }
    private let state = Mutex<State>(.idle)
    private let client: LegacyClient

    init(client: LegacyClient) { self.client = client }

    func start(_ continuation: CheckedContinuation<Data, any Error>) {
        // 1. Publish the continuation first, unless we were already cancelled.
        let cancelled = state.withLock { state -> Bool in
            if case .cancelledBeforeStart = state { state = .finished; return true }
            state = .waiting(continuation, nil, cancelRequested: false)
            return false
        }
        if cancelled {
            continuation.resume(throwing: CancellationError())
            return
        }

        // 2. Start the SDK work. Its callback may fire before this line returns.
        let request = client.fetchData { [self] result in
            finish(result.mapError { $0 as any Error })
        }

        // 3. Record the handle. If a cancel arrived in between, apply it now.
        let cancelNow = state.withLock { state -> Bool in
            guard case .waiting(let c, nil, let cancelRequested) = state else { return false }
            state = .waiting(c, request, cancelRequested: cancelRequested)
            return cancelRequested
        }
        if cancelNow { request.cancel() }
    }

    func finish(_ result: Result<Data, any Error>) {
        let continuation = state.withLock { state -> CheckedContinuation<Data, any Error>? in
            guard case .waiting(let c, _, _) = state else { return nil }
            state = .finished
            return c
        }
        continuation?.resume(with: result)
    }

    func cancel() {
        let request = state.withLock { state -> SDKRequest? in
            switch state {
            case .idle:
                state = .cancelledBeforeStart
                return nil
            case .waiting(let c, nil, _):
                state = .waiting(c, nil, cancelRequested: true) // start() will cancel it
                return nil
            case .waiting(_, let request?, _):
                return request // the SDK reports .cancelled through finish()
            case .cancelledBeforeStart, .finished:
                return nil
            }
        }
        request?.cancel()
    }
}

extension LegacyClient {
    func cancellableData() async throws -> Data {
        let fetch = CancellableFetch(client: self)
        return try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                fetch.start(continuation)
            }
        } onCancel: {
            fetch.cancel()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This version passed every test, including 200 runs that cancel at the same moment the SDK completes. But look at how much of it exists only to handle ordering: cancelled before start, cancelled between start and having the handle, completion racing cancellation. The actual operation is one line. This is exactly the problem SE-0564 was written to solve.

6. SE-0564: split continuations

SE-0564 by Franz Busch was accepted on 18 November 2026, after a review that ran from 4 to 18 November. Its implementation is swiftlang/swift#91981. The Language Steering Group kept the withContinuation name for the new split form, rather than giving it a separate name, because they expect it to become the preferred way to suspend a task.

It builds on SE-0528, implemented in Swift 6.4, which added Continuation<Success, Failure>: a noncopyable continuation. Because every resume method is consuming, resuming it twice is a compile-time error, and dropping it without resuming traps at runtime. SE-0528's withContinuation(of:throwing:_:) still has the classic shape: a synchronous body that receives the continuation, and the task suspends once the body returns.

SE-0564 adds a second form of withContinuation that splits the continuation into two halves:

  • Continuation, the resume half. You hand it to whoever finishes the work. It's the same SE-0528 type, so existing code that resumes a Continuation works unchanged.
  • ContinuationWaiter, the wait half. The task uses it to suspend until the continuation is resumed.

The body receives both halves, and the body is async:

// Requires a toolchain and runtime with SE-0528 and SE-0564 (not compiled for this article)
let value = try await withContinuation(of: Data.self, throwing: SDKError.self) { continuation, waiter in
    // 1. Hand `continuation` to whoever will resume it (this can involve `await`).
    // 2. Then wait, optionally with handlers installed only for the wait.
    return try await waiter.wait()
}
Enter fullscreen mode Exit fullscreen mode

The signature from the proposal:

public nonisolated(nonsending) func withContinuation<
    Success: ~Copyable, Failure: Error, BodyResult: ~Copyable, BodyFailure: Error
>(
    of: Success.Type = Success.self,
    throwing: Failure.Type,
    _ body: nonisolated(nonsending) (
        consuming Continuation<Success, Failure>,
        consuming ContinuationWaiter<Success, Failure>
    ) async throws(BodyFailure) -> BodyResult
) async throws(BodyFailure) -> BodyResult
Enter fullscreen mode Exit fullscreen mode

Some details worth knowing:

  • The body's result and error are independent of the continuation's. You can transform the value, or catch the continuation's error and throw a different one.
  • The continuation can be resumed before wait() is called. wait() then returns right away without suspending.
  • ContinuationWaiter is ~Copyable and ~Escapable. It must be waited on exactly once (every wait is consuming), it can't escape the body, and dropping it without waiting traps.
  • The body can await between creating and waiting, for example to register the continuation with an actor. The old synchronous body couldn't do that. The proposal lists this as the main reason it didn't simply add handler parameters to the old API.

7. What split continuations improve

Cancellation handling

wait has overloads that install handlers only for the duration of the wait:

public nonisolated(nonsending) consuming func wait(
    onCancel handleCancellation: sending (CancellationError.Reason) -> Void
) async throws(Failure) -> sending Success
Enter fullscreen mode Exit fullscreen mode

The handlers are installed when you call wait and removed before it returns. That ordering removes the biggest race from section 5: by the time onCancel can run, you've already registered the operation, so the handler always has something to cancel. The proposal's own example:

func read(into buffer: ReadBuffer) async throws(IOError) -> Int {
    try await withContinuation(of: Int.self, throwing: IOError.self) { continuation, waiter in
        let id = eventLoop.register(.read(fd, buffer), continuation)
        return try await waiter.wait(onCancel: { _ in eventLoop.cancel(id) })
    }
}
Enter fullscreen mode Exit fullscreen mode

Race 2: with a naive withTaskCancellationHandler, onCancel can run before the request exists and the request runs anyway; with SE-0564 the request is registered first, then waiter.wait(onCancel:) installs the handler, which can cancel it

The rules follow withTaskCancellationHandler:

  • If the task is already cancelled when wait is called, onCancel runs inline before the task suspends.
  • It runs at most once and receives the reason the task was cancelled.
  • It can run concurrently with the resumption, on any thread.

That last point means the completion/cancellation race doesn't disappear. You still need exactly one resume. What goes away is the "cancelled before I registered anything" problem, and with it the need to remember cancelled IDs.

Priority escalation

The same wait can install a handler for SE-0462 priority escalation, useful when a queue or thread pool can move work up:

let priority = Task.currentPriority
let job = queue.enqueue(request, priority: priority, resuming: continuation)
return try await waiter.wait(onPriorityEscalated: { _, newPriority in
    guard newPriority > priority else { return }
    queue.escalate(job, to: newPriority)
})
Enter fullscreen mode Exit fullscreen mode

There's a subtle race here: the task could be escalated after you read Task.currentPriority but before the handler is installed. To close it, the escalation handler is always called once when it's installed, with the task's current priority as both arguments. After that it's called for each escalation while the task waits, and those calls never overlap each other.

That's why the guard newPriority > priority matters: the first call often reports the priority you already used. SE-0564 also changes withTaskPriorityEscalationHandler to behave the same way. On older runtimes it doesn't make that first call, and code written with the guard works correctly either way.

Executor-aware resumption with resumeSynchronously

Resuming a continuation today always enqueues the task, even when the code resuming it is the very executor the task will run on. For an event loop doing I/O, that's an extra trip through the job queue on every completion.

SE-0564 adds resumeSynchronously variants on Continuation, CheckedContinuation and UnsafeContinuation. They let the resumer offer its current execution context:

final class EventLoop: SerialExecutor {
    func run() {
        while true {
            for completion in selector.waitForCompletions() {
                // If the task resumes on this event loop, it runs right here
                completion.continuation.resumeSynchronously(
                    returning: completion.bytesRead,
                    isolatedTo: self.asUnownedSerialExecutor()
                )
            }
            runEnqueuedJobs()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

There are three shapes: isolatedTo: a serial executor, on: a task executor, or both. They mirror ExecutorJob.runSynchronously. If the task resumes on the offered executor, it runs inline until its next suspension point, and only then does resumeSynchronously return. If not, the task is enqueued as usual. The offer is best effort, because the task decides where it resumes when it starts waiting.

This isn't a general way to run tasks synchronously, and it isn't a way around actor isolation. The proposal says these methods may only be called from the offered executor's own context, at a point where it could run one of its own jobs, typically inside an executor implementation between jobs. Offering #isolation's executor from inside an actor method is explicitly invalid: it re-enters the actor outside a suspension point and can cause exclusivity violations. Most app code will never call resumeSynchronously. It's for people who write executors and I/O systems.

8. Before and after

Existing continuation approach Split continuation approach
Creating and waiting are coupled in one call Creating (Continuation) and waiting (ContinuationWaiter) are separate
Cancellation handling needs an outer withTaskCancellationHandler, whose handler can run before anything is registered waiter.wait(onCancel:) installs the handler only once you're waiting, after registration
An operation ID or shared state machine is often needed to connect the handler to the work The continuation is registered first, so the handler can refer to the registered operation directly
Priority escalation needs another nested handler and has a race before it's installed wait(onPriorityEscalated:), called once on install with the current priority
The body is synchronous The body is async, so you can await between creating and waiting
Resuming always enqueues the task resumeSynchronously lets an executor run the task inline when it matches

None of this makes existing continuation code wrong. A simple bridge with no cancellation and no timeout, like the first example in this article, is still correct.

9. A practical migration

Here's the same SDK call at each stage.

1. The original callback API

client.fetchData { result in
    switch result {
    case .success(let data): show(data)
    case .failure(let error): showError(error)
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Today: a checked continuation with cancellation (works on any deployment target with Swift concurrency)

This is the CancellableFetch state machine from section 5, about 60 lines, because:

  • the handler can run before the request exists;
  • the request handle only becomes available after starting;
  • completion and cancellation can race.

3. With SE-0528 + SE-0564 (newer toolchain and runtime required, not compiled for this article)

There's one catch first. Continuation is noncopyable, and SE-0528 points out that it can't be captured and consumed inside an escaping closure, because the compiler can't prove the closure runs only once. A callback API needs a small box that a copyable closure can safely take the continuation from:

import Synchronization

/// Lets an escaping callback consume a noncopyable Continuation exactly once.
final class ContinuationBox<Success: Sendable, Failure: Error>: Sendable {
    private let slot: Mutex<Continuation<Success, Failure>?>

    init(_ continuation: consuming Continuation<Success, Failure>) {
        slot = Mutex(consume continuation)
    }

    func resume(with result: sending Result<Success, Failure>) {
        if let continuation = slot.withLock({ $0.take() }) {
            continuation.resume(with: result)
        }
    }
}

extension LegacyClient {
    func data() async throws(SDKError) -> Data {
        try await withContinuation(of: Data.self, throwing: SDKError.self) { continuation, waiter in
            let box = ContinuationBox(continuation)
            let request = fetchData { result in box.resume(with: result) }
            return try await waiter.wait(onCancel: { _ in request.cancel() })
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Same SDK call, two shapes: today's withTaskCancellationHandler plus a five-state machine (~60 lines) vs. SE-0564 withContinuation with continuation and waiter (~5 lines plus a reusable box)

Comparing the two versions:

  • Registration: the request starts before any handler exists, so the handler always has a real request to cancel. There's no cancelledBeforeStart state, no "cancel requested before the handle existed" flag, and no ID bookkeeping.
  • Cancellation: if the task is already cancelled, onCancel runs inline when wait is called, and the SDK reports .cancelled through the normal callback.
  • Resumption: the box still matters, because completion and cancellation can still race. If this SDK didn't call back on cancel, onCancel would call box.resume(with: .failure(.cancelled)) itself. The box guarantees only one resume wins.
  • Missing resume: if the box is ever deallocated while still holding a continuation, the Continuation's deinit traps with a clear message, instead of leaving a silent hang.
  • Errors: the body's errors are independent of the continuation's, so you could catch .cancelled and rethrow CancellationError() if your app prefers that.

Availability: SE-0528 shipped in Swift 6.4. SE-0564 needs a new version of the Swift standard library and runtime, so on Apple platforms it's tied to the OS versions that ship that runtime. Until your minimum deployment target includes it, keep the section 5 pattern, or use both behind an if #available check. Don't assume it works on every iOS version your app supports.

10. Common continuation mistakes: a checklist

Mistake Why it hurts What to do
Resuming twice Checked traps, unsafe is undefined behavior One owner of the continuation. Use a "take once" box (Mutex + take()) when several paths can finish
Forgetting to resume The task hangs forever and holds its resources Make every path end in a resume, especially guard and error paths. Watch for leaked its continuation in logs
Resuming from several concurrent callbacks A boolean flag is a data race Check and update under a lock, or move the state into an actor
Ignoring cancellation The work keeps running after the user leaves; the task waits for nothing Cancel the underlying operation from a cancellation handler, or from wait(onCancel:) with SE-0564
Capturing continuation state wrongly Mutable vars shared between callbacks race, and Swift 6 will flag them Keep shared state in a Sendable box guarded by a lock
Assuming cancellation resumes the continuation It never does; the task stays suspended until you resume it Make sure a cancelled operation still ends in exactly one resume (usually via the SDK's cancelled callback)
Using UnsafeContinuation without proof Removes the only safety net you had Default to checked, or to Continuation on Swift 6.4+. Use unsafe only for measured hot paths with obviously single resumption
Assuming resume runs the task immediately Code after await runs later, on the task's own executor Don't rely on ordering between the callback thread and the resumed code
Calling resumeSynchronously from the wrong context Can re-enter actors outside suspension points and break exclusivity Only call it from inside an executor's own job loop, offering that executor

11. Conclusion

Continuations aren't just syntax that turns callbacks into await. They're a synchronization boundary between two worlds with different rules. The callback side doesn't know about tasks, cancellation or priorities. The async side assumes every await ends exactly once. Making those two agree is the real job, and most continuation bugs happen because it's treated as a one-liner.

SE-0528 moved the "exactly once" rule into the type system. SE-0564 fixes the structure around it. By separating the half that resumes from the half that waits, you register the work first and then wait with cancellation and priority handlers installed. The ordering problems that used to need a hand-written state machine mostly disappear. What remains, completion racing cancellation, is smaller and easier to reason about.

What's the worst continuation bug you've shipped or debugged: a task that hung forever, or a crash that only showed up under load? I'd like to hear how you tracked it down.


References

Top comments (0)