16 of 22 · Callbacks and concurrency
Delegate
Delegation lets an object hand off decisions or report events to one other object through a protocol. The delegating object holds its delegate weakly so the two don't retain each other.
How it's wired
- The picker defines PumpkinPickerDelegate.
- Its owner conforms and receives didPick.
- The picker never knows its owner's type.
| Part | Owns | Looks like |
|---|---|---|
| Delegating object | Ask or tell its delegate | weak var delegate |
| Protocol | The conversation's contract | protocol PumpkinPickerDelegate: AnyObject |
| Owner | Conforms and answers | Parent view controller |
What bites in practice
- Always weak var delegate, with an AnyObject-constrained protocol. A strong delegate is a retain cycle.
- An optional delegate with optional methods creates a silent "nobody answered" path. If an answer is required, take a closure or a non-optional dependency in init.
- Name methods with the source first, picker(_:didPick:), so one object can delegate for several sources.
- Only one listener. If several parts of the app care, you want pub/sub or an observable model.
When I'd use a delegate
| A component with several related callbacks | Delegate, UIKit style. |
|---|---|
| One callback | A closure. |
| Broadcasts | Pub/sub or an observable model. |
Compared
Delegate vs closure vs pub/sub
| Delegate | Closure | Pub/sub | |
|---|---|---|---|
| Listeners | One | One | Many |
| Several related events | Natural | One closure each | Event enum |
| Retain-cycle risk | If not weak | Capture lists | Token lifetime |
Expert notes
- Delegates are for conversations, pub/sub is for broadcasts.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Delegate in 30 seconds.
- Delegation hands decisions or events from one object to exactly one owner through a protocol, like a table view asking its data source.
- The delegate is held weakly to avoid a retain cycle.
- It fits a component with several related callbacks and one listener.
- For a single callback I use a closure, for many listeners pub/sub, and if an answer is required I take it in init instead.
Delegate protocol or closures: how do you choose for a component's callbacks in Swift?
- Use a closure for a single callback, ideally passed in
init, so there's no ambiguous nil delegate when a decision is needed. - Use a delegate for many related events, since it groups them in one type.
- The gotcha with closures is retain cycles when they capture the owner, so use
[weak self]. - For several closures, group them in a configuration struct.
After adding a delegate to your custom component, neither the component nor its owning screen ever deallocates. What happened?
- It's a retain cycle.
- The owner holds the component, and the component holds the owner as its delegate.
- Declare
weak var delegate: ComponentDelegate?and constrain the protocol toAnyObject. - Also follow the conventions.
- Methods start with the delegating type's name and pass the delegating object first, like
func picker(_ picker: Picker, didSelect item: Item).
A tap inside a deeply nested child view controller must trigger navigation owned several levels up. How do you route it?
- Relay it up the delegate chain.
- The child calls its delegate, each parent forwards the intent until it reaches the controller that owns the navigation controller, and that one navigates.
- Children never reach sideways or walk up the hierarchy, so each stays reusable anywhere.
- The cost is relay boilerplate at each level, and coordinators exist partly to shorten that chain.
Two reusable components on one screen both need to be the scroll view's delegate. UIKit allows only one. What do you do?
- Put a multiplexing proxy in the delegate slot that forwards each call to several targets.
- The gotcha is
responds(to:). - If the proxy only checks the first target, UIKit may skip callbacks that another target implements, so check every target.
- Also decide who wins for callbacks that return values, like
scrollViewShouldScrollToTop(_:).