Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 146 ยท Concurrency

Bridging Callbacks to async

Learn how to wrap callback-based and delegate-based APIs in async functions with withCheckedContinuation and withCheckedThrowingContinuation, the resume-once rule, cancellation and AsyncStream bridges.

Swift's async/await is young. Foundation, the operating system frameworks and thousands of third-party libraries were written years earlier, when "tell me when you are done" meant a callback: a closure passed to a function that calls it later. You cannot await a callback. But you do not have to rewrite those libraries, and you do not have to give up on await in your own code. Swift provides a small bridge called a continuation.

A continuation is a handle to a suspended task. You suspend the current task, start the old callback-based work, and in the callback you resume the task with the result. From outside, the wrapper looks like any other async function. This lesson shows how to write that bridge safely, what happens if you get it wrong, how to handle cancellation, and what to do with callbacks that fire more than once. It follows AsyncSequence and AsyncStream and Cancellation and Timeouts.

The old callback style

Here is a typical callback API. It does its work in the background and calls completion on some other thread when it is ready. (We use Dispatch from Foundation to imitate a slow operation. See Threads and Dispatch later in this chapter.)

Swift
// read-only sketch of the shape of such an API
func loadName(id: Int, completion: @escaping @Sendable (String) -> Void)

The function returns immediately, and the result arrives later through the closure. This is awkward to combine with other work: you cannot write let name = loadName(id: 7), and chaining several such calls leads to nesting that Introduction to Swift Concurrency showed.

withCheckedContinuation

withCheckedContinuation suspends the current task and gives you a continuation value. You hand the continuation's resume to the callback. When the callback runs, the task wakes up and the value you resumed with becomes the result of the await.

Swift Wrapping a callback in an async function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints user-7 and then user-1 user-2. Both overloads share a name, and Swift picks the right one: the one with a completion closure when you pass a closure, and the async one when you await. From now on, callers see an ordinary async function, and can combine it with async let and task groups like anything else.

Let us take apart what happens:

  1. await withCheckedContinuation { ... } suspends the calling task. The body closure runs immediately, before the suspension takes effect, and receives the continuation.
  2. The body starts the callback API and returns. It must not wait.
  3. Some time later the callback runs, on whatever thread the library uses, and calls continuation.resume(returning:).
  4. The task is scheduled to continue, and withCheckedContinuation returns the value.

The type of the continuation is CheckedContinuation<T, E>: T is the result type and E is the error type (Never for the non-throwing version). Swift usually infers both from how you use the result. When it cannot, annotate: await withCheckedContinuation { (c: CheckedContinuation<Int, Never>) in ... }.

Errors: withCheckedThrowingContinuation

Callback APIs report failure in two common ways: a Result parameter, or two optional parameters (value, error). Use the throwing variant and resume with resume(throwing:) for failure, or pass the Result directly with resume(with:).

Swift withCheckedThrowingContinuation and Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is item 3 and failed: notFound(42). The thrown error is exactly the one the library produced, and callers handle it with do/catch as in Error Handling. For an API with (Data?, Error?) parameters, write the check yourself:

Swift
// read-only sketch
if let error {
    continuation.resume(throwing: error)
} else if let data {
    continuation.resume(returning: data)
} else {
    continuation.resume(throwing: URLError(.unknown))   // neither: never leave it unresumed
}

The last branch matters. Whatever the library does, every path must resume.

The golden rule: resume exactly once

A continuation must be resumed exactly one time, on every path. This is the rule you must never forget, and the "checked" in withCheckedContinuation is there to catch mistakes. Both kinds of mistake are possible:

Resuming twice is a bug in your wrapper, such as a library that calls the callback twice. The checked continuation crashes the program on the second resume:

Swift Resuming a continuation twice (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program is killed by a signal and stderr contains Fatal error: SWIFT TASK CONTINUATION MISUSE: binary tried to resume its continuation more than once, returning 2! followed by a backtrace (the runner shows type names as binary). The first resume succeeded, and the second one is the crash. The words "returning 2" tell you which value arrived second.

Never resuming is the opposite bug. The task stays suspended forever, so a Task that awaits it never finishes and a for loop around it never advances. Nothing crashes. The checked continuation helps by logging a warning when the continuation is thrown away without being resumed:

Swift Never resuming a continuation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The standard output is giving up waiting; the task is still suspended, and stderr shows SWIFT TASK CONTINUATION MISUSE: binary leaked its continuation without resuming it. This may cause tasks waiting on it to remain suspended forever. That message is a log line, not a crash, so it is easy to miss. Remember it: if an await hangs, look for a continuation that is not resumed on some path (an early return, an error branch, a callback that is never called).

The check costs a tiny bit of performance but is almost always worth it. There is an unchecked sibling, withUnsafeContinuation / withUnsafeThrowingContinuation, with the same API and no safety net: mistakes become undefined behavior instead of a clear message. Use the checked versions, and switch to unsafe only in a measured hot path that is already proven correct.

Bridging a delegate or a stored completion

A callback is not always passed as an argument. Sometimes you tell an object to start work, and it calls you back later through a delegate method. You can still bridge it: store the continuation where the delegate method can find it. Because several tasks may call at once, keep it inside an actor.

This example is a small "gate": tasks wait until another part of the program opens it. The waiting tasks hold continuations, and openGate resumes them all.

Swift Storing continuations in an actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see opening the gate, first passed, second passed. Notice waiter.resume() with no argument: for a Void continuation, resume() is shorthand for resume(returning: ()). The actor makes sure the list is not changed by two tasks at once, and clearing waiters after resuming ensures no continuation is resumed twice. A later call to wait() returns at once because isOpen is true.

Look at the order of operations inside wait(): the closure passed to withCheckedContinuation runs synchronously on the actor, so appending the continuation is atomic with the isOpen check. If you checked isOpen before and appended after a suspension, a open() call could slip in between, and the waiter would hang forever. This is the reentrancy trap from the Actors lesson in a new disguise.

When the callback fires many times

A continuation resumes once. Many APIs call back repeatedly: a timer ticking, a sensor, a download reporting progress, a delegate receiving messages. For those, do not use a continuation. Use an AsyncStream and yield every time the callback fires, then finish() when the source is done.

Swift A repeating callback becomes an AsyncStream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is tick 1, tick 2, tick 3, ticker finished. The @unchecked Sendable on the toy class is our promise that it is safe: it has no state at all. In a real wrapper, a legacy class that you do not own often needs this too; the Sendable lesson explains when that promise is honest.

Rule of thumb: one answer: continuation. A series of answers: AsyncStream.

Supporting cancellation

When a task awaiting your wrapper is cancelled, the wrapper does not notice by itself: the task stays suspended until the callback arrives. If the old API has a way to cancel, connect it with withTaskCancellationHandler. The onCancel closure runs as soon as the task is cancelled, and your wrapper asks the library to stop. A good library then calls the completion with an error, and the continuation is resumed as usual.

Swift Wiring cancellation to a legacy cancel method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call prints 42. The second task is cancelled after 30 ms. The handler flips the job's flag, the legacy code sees it when its timer fires and reports CancellationError, the continuation is resumed with that failure, and the program prints compute failed: CancellationError(). A Mutex holds the job because onCancel can run on a different thread at the same time as the operation body.

There is a gap in this simple version: if the task is cancelled before the job has been stored, onCancel runs with running still empty and nothing is cancelled. Production code closes the gap by also remembering "cancelled already" and checking it after storing the job. For small wrappers the gap is acceptable, but be aware of it.

Design checklist for a wrapper

  • One resume per path. Trace every if, guard and return in the callback and make sure each one resumes the continuation, once.
  • Call the old API inside the continuation body, and do not await anything in that body (it is a plain synchronous closure).
  • Choose the throwing variant when the callback can report an error, and forward the library's error unchanged.
  • Use AsyncStream for callbacks that fire repeatedly.
  • Think about threads. The callback usually runs on a thread you do not control. That is fine: resuming a continuation is safe from any thread.
  • Expose only the async function. Keep the continuation private inside the wrapper so callers cannot resume it twice.
  • Do not wrap code that is already async. If a library offers an async version, use it. Wrapping is only for old APIs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a continuation used for?

    A continuation represents a suspended task. You resume it from the callback, so the wrapper looks like a normal async function.
  2. 2. How many times must a continuation be resumed?

    Resuming twice crashes a checked continuation. Not resuming leaves the task suspended forever. Even failures must resume, with resume(throwing:).
  3. 3. A callback-based function reports its outcome as Result<String, Error>. What is the shortest correct bridge?

    resume(with:) takes a Result and either returns its value or throws its error, so the throwing variant fits.
  4. 4. A library calls its progress callback 50 times. Which bridge fits?

    A continuation can only be resumed once. A repeating callback produces a series of values, which is what AsyncStream is for.
  5. 5. Your await on a wrapper never returns and stderr shows leaked its continuation without resuming it. What is the likely cause?

    That log line means the continuation was thrown away unresumed, so the awaiting task stays suspended forever.

Summary

  • A continuation lets you turn a callback-based API into an async function: suspend with withCheckedContinuation, start the old work, and resume from the callback.
  • Use withCheckedThrowingContinuation when the callback can fail; resume(with:) forwards a Result, resume(throwing:) forwards an error, and resume() finishes a Void continuation.
  • Resume exactly once on every path. A second resume traps with SWIFT TASK CONTINUATION MISUSE: ... more than once; a missing resume leaves the task suspended forever and logs a "leaked its continuation" message.
  • Store continuations in an actor when delegates or later events must resume them.
  • Repeating callbacks belong in an AsyncStream, not a continuation.
  • Combine a wrapper with withTaskCancellationHandler to call the old API's cancel method when the task is cancelled.
  • Prefer the checked versions over withUnsafeContinuation, and use native async APIs where they exist.

Next: Threads and Dispatch looks at the older threading tools that sit underneath all this, and how they relate to Swift concurrency.