# Bridging Callbacks, Delegates and GCD

## Checked continuations

`withCheckedContinuation` (non-throwing) and `withCheckedThrowingContinuation`
(throwing) turn a completion-handler API into an async function. Both are
available from iOS 13. Documentation:

- https://developer.apple.com/documentation/swift/withcheckedcontinuation(isolation:function:_:)
- https://developer.apple.com/documentation/swift/withcheckedthrowingcontinuation(isolation:function:_:)

```swift
func fetchQuote(for symbol: String) async throws -> Quote {
    try await withCheckedThrowingContinuation { continuation in
        legacyMarket.requestQuote(symbol) { result in
            switch result {
            case .success(let quote):
                continuation.resume(returning: quote)
            case .failure(let error):
                continuation.resume(throwing: error)
            }
        }
    }
}
```

### Rules

- Resume exactly once.
- Never resuming leaves the awaiting task suspended forever: a leak that no
  error reports.
- Resuming twice traps at run time.
- Use checked continuations by default; they detect both mistakes and log
  diagnostics. `withUnsafeContinuation` is for measured hot paths whose
  correctness is already established.
- The continuation outlives the closure it was handed to, so every exit path,
  including errors and cancellation, must resume it.

## Bridging a delegate

Store the continuation, resume it from the delegate callbacks, and clear it
after resuming so it cannot be resumed again.

```swift
import CoreLocation

@MainActor
final class OneShotLocator: NSObject, @preconcurrency CLLocationManagerDelegate {
    private let manager = CLLocationManager()
    private var pending: CheckedContinuation<CLLocation, any Error>?

    override init() {
        super.init()
        manager.delegate = self
    }

    func currentLocation() async throws -> CLLocation {
        try await withCheckedThrowingContinuation { continuation in
            pending = continuation
            manager.requestLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let first = locations.first else { return }
        pending?.resume(returning: first)
        pending = nil
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        pending?.resume(throwing: error)
        pending = nil
    }
}
```

The `@preconcurrency` conformance lets the Objective-C delegate protocol be
satisfied by main-actor methods and checks at run time that the callbacks
really arrive on the main thread, which is where a manager created on the main
thread delivers them.

## Passing cancellation through

Keep a handle to the legacy operation and cancel it from `onCancel`:

```swift
func downloadReport(id: String) async throws -> Data {
    let handle = ReportRequestHandle()
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            handle.request = legacyReports.download(id: id) { result in
                continuation.resume(with: result)
            }
        }
    } onCancel: {
        handle.request?.cancel()
    }
}
```

`ReportRequestHandle` is a small `Sendable` box (for example a final class with
a `Mutex`-protected property) because `onCancel` can run on any thread. The
legacy API must still call its completion with a cancellation error so the
continuation resumes.

## Streams from repeating callbacks

For sources that produce many values over time, such as delegates or
`NotificationCenter`, build an `AsyncStream`:

```swift
@MainActor
func locationUpdates() -> AsyncStream<CLLocation> {
    AsyncStream { continuation in
        let feed = LocationFeed { continuation.yield($0) }
        continuation.onTermination = { _ in
            Task { @MainActor in feed.stop() }
        }
        feed.start()
    }
}
```

`LocationFeed` is a `@MainActor` delegate object like `OneShotLocator` that
calls its closure from `didUpdateLocations` and starts or stops updates on its
manager. Setting `onTermination` stops the source
when the consumer stops iterating or its task is cancelled.

## Replacing GCD

This table applies the rule in SKILL.md, "Choosing how code moves between
contexts": prefer isolation written in declarations, use a dynamic hop only
when a declaration cannot express it, and keep Dispatch only where an API
insists on a queue.

| GCD | Preferred replacement | Fallback, with its reason |
|---|---|---|
| `DispatchQueue.main.async { }` | `@MainActor` on the function, type or closure | `Task { @MainActor in }` from synchronous code; `await MainActor.run { }` for one batch inside an async function that must stay `nonisolated` |
| `DispatchQueue.global().async { }` | A `@concurrent` async function (Swift 6.2) | `Task { }` when inheriting the caller is fine; `Task.detached { }` only to shed actor, priority and task-locals on purpose |
| `DispatchGroup` | `async let` or a task group | |
| `DispatchSemaphore` | Actor isolation, or an `AsyncStream` to hand values between tasks | |
| `DispatchWorkItem` with `cancel()` | A stored `Task` and `task.cancel()` | |
| Serial `DispatchQueue` guarding state | An `actor` | A `Mutex` when callers are synchronous |
| `DispatchQueue.concurrentPerform` | `withTaskGroup` | |
| `DispatchSource.makeTimerSource` | A loop around `try await Task.sleep(for:)`, or a `Clock` | |
| A queue required by an API (`NWConnection.start(queue:)`, capture output delegates) | Keep the queue; enter isolation immediately in the callback | Make the queue the executor of a custom actor via `DispatchSerialQueue` (iOS 17) |

### Group to task group

Before:

```swift
let group = DispatchGroup()
var pages: [Data] = []
for url in pageURLs {
    group.enter()
    fetchPage(url) { data in
        if let data { pages.append(data) }   // unsynchronized append
        group.leave()
    }
}
group.notify(queue: .main) { self.show(pages) }
```

After:

```swift
let pages = await withTaskGroup(of: Optional<Data>.self, returning: [Data].self) { group in
    for url in pageURLs {
        group.addTask { try? await fetchPage(url) }
    }
    var collected: [Data] = []
    for await case let page? in group {
        collected.append(page)
    }
    return collected
}
show(pages)
```

### Serial queue to actor

Before:

```swift
final class TokenStore {
    private let queue = DispatchQueue(label: "token-store")
    private var tokens: [String: String] = [:]

    func save(_ token: String, for account: String) {
        queue.async { self.tokens[account] = token }
    }
}
```

After:

```swift
actor TokenStore {
    private var tokens: [String: String] = [:]

    func save(_ token: String, for account: String) { tokens[account] = token }
    func token(for account: String) -> String? { tokens[account] }
}
```
