skip to content

How do you wrap a legacy Swift location SDK's `requestLocation(completion:)` callback in an `async throws` function using `withCheckedThrowingContinuation`?

level: middleimportance: must knowfreq 60%

answer

  1. suspend now, resume from the callback
  2. the closure runs immediately
  3. one resume on every path
  4. Result maps to resume(with:)
  5. Objective-C may already be async

basics

~10 s

Call the SDK inside withCheckedThrowingContinuation and, in its completion handler, resume the continuation exactly once: resume(returning:) with the location or resume(throwing:) with the error. Callers then simply try await the wrapper.

solid answer

~40 s

Write an `async throws` method whose body is `try await withCheckedThrowingContinuation { continuation in ... }`. The closure runs **immediately**, on the calling task, and the task suspends once it returns. Inside it, call `requestLocation(completion:)` and, in the completion handler, call exactly one resume method on every path: `resume(returning:)` with the coordinate, `resume(throwing:)` with the error, or `resume(with:)` when the callback hands you a `Result`. `CheckedContinuation` is `Sendable`, so the handler may resume it from whatever queue the SDK uses; `resume` returns at once and the awaiting task carries on when its executor schedules it. Use `withCheckedContinuation` when the call cannot fail. Before writing one, check whether the API is Objective-C: the compiler already imports the completion-handler methods it recognises as `async` functions too.

code

swift · 37 lines
swift
import Foundation

struct Coordinate: Sendable { let latitude: Double; let longitude: Double }
enum LocationError: Error { case noFix }

// The legacy SDK: calls back once, on a queue of its choosing.
final class LegacyLocationSDK: Sendable {
    func requestLocation(completion: @escaping @Sendable (Coordinate?, Error?) -> Void) {
        DispatchQueue.global().async {
            completion(Coordinate(latitude: 59.91, longitude: 10.75), nil)
        }
    }
}

extension LegacyLocationSDK {
    func currentLocation() async throws -> Coordinate {
        try await withCheckedThrowingContinuation { continuation in
            // This closure runs at once, on the calling task, before it suspends.
            requestLocation { coordinate, error in
                if let error {
                    continuation.resume(throwing: error)
                } else if let coordinate {
                    continuation.resume(returning: coordinate)
                } else {
                    continuation.resume(throwing: LocationError.noFix)  // the "neither" path
                }
            }
        }
    }
}

@main struct Main {
    static func main() async throws {
        let here = try await LegacyLocationSDK().currentLocation()
        print(here.latitude, here.longitude)
    }
}

go deeper

for a junior

Recall that a continuation turns a callback into an async function and must be resumed with the result or the error.

for a middle

Explain the recipe: the closure runs at once, the task suspends, and each callback path calls exactly one resume method, with resume(with:) for a Result.

for a senior

Show where wrappers go wrong in production: the neither-value-nor-error path, delegate storage, multi-value APIs and cancellation that never reaches the SDK.

for a principal

Decide where a codebase draws its async boundary around legacy SDKs, and when to wrap per call versus replace the SDK.

## What a continuation is A **continuation** is a handle to a suspended task: whoever holds it can make that task resume, either returning a value or throwing an error. Swift's standard library exposes it through four functions: - `withCheckedContinuation(function:_:)`, for a non-throwing wrapper; - `withCheckedThrowingContinuation(function:_:)`, for a throwing wrapper; - `withUnsafeContinuation(_:)` and `withUnsafeThrowingContinuation(_:)`, the same without run-time checks. Each one passes a continuation to a closure that you write, then suspends the calling task until that continuation is resumed. Whatever you pass to the resume call becomes the return value, or the thrown error, of the `with...` call. That is exactly the shape needed to turn a callback into an `async` function. The checked variants also take a `function:` argument that defaults to `#function`; it names your wrapper in the run-time misuse messages, so leave it at its default. ## The wrapping recipe 1. Declare the wrapper: `func currentLocation() async throws -> Coordinate`. 2. Return `try await withCheckedThrowingContinuation { continuation in ... }`. 3. Inside the closure, call the legacy method, `requestLocation(completion:)`, and let its completion handler capture `continuation`. 4. In the handler, map every outcome to exactly one resume call. A handler that receives `(Coordinate?, Error?)` has three paths: an error, a coordinate, and the "neither" case, which still needs a resume, usually with an error of your own. 5. Callers write `let here = try await sdk.currentLocation()` and never see the callback. The both-`nil` path is the one most often missed. The SDK's documentation rarely mentions it, but a `(Coordinate?, Error?)` signature allows it, and the compiler cannot tell that a branch forgot to resume: the code compiles, and the caller waits forever on the day that branch runs. The closure runs **at once**, on the calling task, before the task suspends; the standard library's doc comment says the body "executes synchronously on the calling task, and once it returns the calling task is suspended". So it is the right place to start the request, but not to wait for anything. ## Mapping the callback to resume calls | The callback delivers | Resume with | |---|---| | a value | `resume(returning:)` | | an error | `resume(throwing:)` | | a `Result<T, E>` | `resume(with:)` | | nothing, on a `Void` wrapper | `resume()` | `resume(with:)` switches over the `Result` for you. `resume()` exists only when the result type is `Void`. A checked continuation's closure takes no `throws`, so an error must travel through `resume(throwing:)`. ## Threads and isolation - The closure runs in the caller's isolation: called from a `@MainActor` method, it may touch main-actor state, and this compiles in Swift 6 language mode. - The SDK may call back on any queue. `CheckedContinuation` is `Sendable`, so capturing it in a `@Sendable` completion handler and resuming it from a background thread is fine. - `resume` only enqueues the awaiting task and returns at once; the task continues when its executor schedules it. A main-actor caller therefore carries on on the main actor, even though the SDK answered on a background queue. ## Before you write a wrapper - **Objective-C APIs may already be async.** When Swift recognises an Objective-C method's block parameter as a completion handler, through an explicit `swift_async` attribute or naming rules such as a last parameter called `completionHandler` or `completion`, it imports the method both as written and as an `async` function (Swift Evolution's Objective-C concurrency interoperability proposal, Swift 5.5). Check the generated interface first. - **Delegate APIs work too.** Store the continuation in a property when the request starts and resume it from the delegate callback, then set the property to `nil`. - **One answer per wrapper.** A continuation resumes once; an API that reports many values, such as location updates, belongs in an asynchronous stream instead (covered in the lesson on async sequences). - **Cancellation does not reach the SDK by itself.** Cancelling the awaiting task neither resumes the continuation nor stops the request; wiring that up is covered in the lesson on cancellation. - **Keep the checked variant.** The checks are cheap; what goes wrong when a continuation is resumed twice or never is a question of its own. - **Test every path.** Drive the wrapper with a fake SDK that answers at once, answers later on another queue, and reports an error, so each resume call is exercised before real users find the path you missed.

  • When does the closure passed to `withCheckedThrowingContinuation` run, and when does the caller suspend?
    The closure runs immediately and synchronously on the calling task; the task suspends only after the closure returns. So the closure should start the request and hand the continuation to the callback, not wait for anything. If the callback fires before the closure has even returned, the task does not wait: it continues as soon as the closure returns and its executor schedules it.
  • The SDK's completion handler gives you a `Result<Coordinate, Error>`. What is the shortest correct wrapper body?
    Pass the result straight through: `requestLocation { result in continuation.resume(with: result) }`. `resume(with:)` returns the success value or throws the failure, so one call covers both paths and the exactly-once rule holds by construction.
  • Do you need to wrap an Objective-C method that takes a completion handler?
    Often not. Since Swift 5.5 the compiler imports a method whose block it recognises as a completion handler, by a `swift_async` attribute or by naming rules such as a last parameter named `completionHandler`, twice: as written, and as an `async` function. Call the `async` form with `await`, and keep hand-written continuations for C callbacks, Swift-only SDKs and delegate protocols.

A restaurant pager: you order, take the pager and sit down, and the counter serves other customers. The kitchen must buzz your pager exactly once when the food is ready; a pager that never buzzes leaves you waiting all night.

  • The continuation closure runs later, on a background thread
  • Resuming from the SDK's background queue is a data race
  • An error can be thrown out of the continuation closure instead of resumed
  • One continuation can deliver every location update the SDK reports
  • Objective-C completion-handler methods can only be called with a closure from Swift
  • Cancelling the awaiting task resumes the continuation automatically