SwiftPumpkin

18 of 22 · Callbacks and concurrency

Completion Handlers

A completion handler is an escaping closure an asynchronous API calls when its work finishes, usually with a Result. The contract is: call it exactly once, on every path.

How it's wired

send(_:completion:)completion(Result)CallerContinues laterAsync APIDoes work
calls or tellsreports backThe contract is "exactly once, on every path", and nothing enforces it.
  • An @escaping closure parameter called with a Result when async work finishes.
PartOwnsLooks like
CallerPass a closure, continue inside itAPI call with trailing closure
CalleeCall completion exactly once@escaping (Result<T, Error>) -> Void

Why it's error-prone

  • Nothing enforces exactly-once. A missing return after calling completion fires it twice; an early return without calling it leaves a spinner forever.
  • Which thread? Undocumented callback threads mean someone updates UI off the main thread.
  • Escaping closures capture strongly by default. Use [weak self] when the callee can outlive the caller.
  • Sequential calls nest into a pyramid, and error handling repeats at every level.

When I'd still write one

Objective-C interop or old deployment targetsCompletion handlers.
New Swift codeasync/await, with continuations to wrap what's left.

Compared

Completion handler vs async/await

Completionasync/await
Exactly onceBy conventionGuaranteed by the compiler
ErrorsResult in each callbackthrows / try
CancellationManualTask cancellation
ThreadingDocumented, hopefullyActor isolation

Expert notes

  • Every path calls completion once. Use defer or a single exit if you have to keep the style.

Check yourself

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

30-second answer

Explain Completion Handlers in 30 seconds.

SwiftAsked directly

What's wrong with a completion handler taking Data? and Error?, and how does Result fix it?

SwiftAsked indirectly

Code review finds a function with several early returns that sometimes never calls its completion. How do you prevent this bug class?

iOS codingAsked indirectly

A view model stores a completion closure that references the view controller, and the screen never deallocates. Fix it.

SwiftAsked directly

Swift has throws. Why would you still pass a Result value?

Read it in the app's source