SwiftPumpkin

19 of 22 · Callbacks and concurrency

Promises → async/await

Futures and promises turn "call me back" into a value that represents a result arriving later. Swift's async/await makes that part of the language: an async function suspends, then returns or throws exactly once.

How it's wired

awaitreturns / throwsCallsresume(with:)Callertry awaitContinuationBridges callbackLegacy APICompletion handler
calls or tellsreports backThe compiler guarantees an async function returns once. The continuation enforces it at the bridge.
  • Combine's Future is a one-shot promise. async functions return or throw exactly once. withCheckedThrowingContinuation bridges old callbacks.
PartOwnsLooks like
async functionReturns or throws exactly oncefunc send() async throws
ContinuationWrap a callback APIwithCheckedThrowingContinuation
FutureOne-shot value object (Combine)Future<Output, Failure>

What staff engineers watch for

  • Bridging: wrap callback APIs with withCheckedThrowingContinuation. It traps on a double resume and logs if never resumed. Unsafe continuations remove those checks.
  • Cancellation is cooperative. Cancelling a Task doesn't stop the callback API underneath; use withTaskCancellationHandler to cancel the real work.
  • Task {} is unstructured: no automatic cancellation, and it inherits the current actor. Prefer async let and task groups, and .task in SwiftUI so work dies with the view.
  • Actor reentrancy: across an await inside an actor, state can change. Re-check invariants after every suspension point.

What I'd use

New one-shot async workasync/await.
Streams of valuesAsyncSequence, or Combine where you need operators.
Legacy callback APIsWrap once in a checked continuation.

Compared

Future vs async/await vs AsyncSequence

Futureasync/awaitAsyncSequence
ValuesOneOneMany
CancellationCancel subscriptionTask cancellationCancel the consuming task
ErrorsFailure typethrowsthrows per element

Expert notes

  • Structured concurrency is the point: work that can't outlive its scope can't leak.

Check yourself

Answer out loud before you reveal. Recall is what makes it stick.

30-second answer

Explain Promises → async/await in 30 seconds.

SwiftAsked directly

How do you wrap a completion-handler API with async/await, and which rule must never be broken?

SwiftAsked indirectly

Profiling shows checked continuations in a hot path. Can you switch to unsafe ones, and what do you give up?

iOS codingAsked indirectly

A UIKit button handler must call an async method and show errors. How do you bridge sync and async?

Read it in the app's source