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
- An @escaping closure parameter called with a Result when async work finishes.
| Part | Owns | Looks like |
|---|---|---|
| Caller | Pass a closure, continue inside it | API call with trailing closure |
| Callee | Call 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 targets | Completion handlers. |
|---|---|
| New Swift code | async/await, with continuations to wrap what's left. |
Compared
Completion handler vs async/await
| Completion | async/await | |
|---|---|---|
| Exactly once | By convention | Guaranteed by the compiler |
| Errors | Result in each callback | throws / try |
| Cancellation | Manual | Task cancellation |
| Threading | Documented, hopefully | Actor 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.
Explain Completion Handlers in 30 seconds.
- A completion handler is an escaping closure an async API calls when it finishes, usually with a Result.
- The contract is exactly once on every path, and nothing enforces it: a missing return fires it twice, an early return never calls it.
- The callback thread must be documented, and self is captured strongly by default.
- In new code I use async/await, where exactly-once is a language guarantee.
What's wrong with a completion handler taking Data? and Error?, and how does Result fix it?
- With
(Data?, Error?), both can be nil or both set, so callers face states that make no sense, and the compiler can't prove the data exists. Result<Data, Error>has exactly two cases, success with a value or failure with an error, and the compiler forces callers toswitchover both.- Today
async throwsgives the same guarantee with less ceremony.
Code review finds a function with several early returns that sometimes never calls its completion. How do you prevent this bug class?
- Move to async/await.
- Forgetting to call the completion on an early return, or forgetting to return after calling it, is a whole bug class the compiler can't catch with callbacks.
- An
async throwsfunction must return a value or throw on every path, so the compiler enforces it. - Nesting and verbose error paths go away too.
A view model stores a completion closure that references the view controller, and the screen never deallocates. Fix it.
- Escaping closures are stored, so they retain whatever they capture.
- A view model holding a closure that captures the controller is a cycle.
[weak self]fixes it, but the compiler won't warn when you forget.- A safer habit is capturing only what you need, like
[label = self.label], so the controller never enters the closure.
Swift has throws. Why would you still pass a Result value?
- Throws only propagates an error up the current call stack.
- It can't be stored, moved between threads, or handed to another function later.
Resultis a plain value, so it can do all of that, which is why callback APIs used it.- The gotcha is that the compiler forces you to handle a throw, but a
Resultcan be silently ignored.