14 of 20 · 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 |
Swift example: retain-cycle delegate vs. weak AnyObject protocol
A strong delegate creates a retain cycle whenever the parent holds the child and the child holds the parent as its delegate.
Before vs. after: weak delegate + source-first naming
Constrain the protocol to AnyObject so weak var compiles; pass the sender first so one parent can distinguish multiple pickers.
// ❌ Before: strong reference -> ParentVC retains PickerVC retains ParentVC (leaks).
protocol LeakyPickerDelegate { func didPick(_ item: String) }
final class LeakyPickerVC: UIViewController {
var delegate: (any LeakyPickerDelegate)? // STRONG!
}
// ✅ After: AnyObject + weak var breaks the cycle.
@MainActor
protocol PumpkinPickerDelegate: AnyObject {
func picker(_ picker: PumpkinPickerVC, didPick item: String)
func pickerDidCancel(_ picker: PumpkinPickerVC)
}
final class PumpkinPickerVC: UIViewController {
weak var delegate: (any PumpkinPickerDelegate)?
func userSelected(_ item: String) {
delegate?.picker(self, didPick: item)
}
}If a component only has one callback (no multi-event conversation), a plain closure onPick: (String) -> Void is lighter.
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.
- A delegate is one owner answering a component's questions and events through a protocol, the way a table view asks its data source.
- The component holds it
weak, which breaks the ownership cycle. - I'd use it when there are several related callbacks and exactly one listener.
- A single callback gets a closure, and broadcasts get pub/sub.
- The risk is silence, because an optional delegate nobody set just does nothing.
- So when an answer is required, I take a closure in
init.
Delegate protocol or closures: how do you choose for a component's callbacks in Swift?
- I choose by the shape of the conversation.
- One event, or one required answer, gets a closure in
init, so the dependency can't be forgotten. - Several related events for one owner get a delegate protocol, because it groups them in one documented type and default extensions let conformers implement only what they need.
- Closures cost a deliberate capture list each, while a delegate is a single
weakreference. - I'd standardize the convention per layer, so reviewers and AI agents don't have to guess.
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 screen owns the component strongly, and the component holds the screen as a strong delegate, so neither reference count reaches zero.
- I'd declare
weak var delegate: PickerDelegate?and constrain the protocol toAnyObject, becauseweakonly applies to class references. - Then I'd confirm it in Xcode's Memory Graph Debugger, rather than trusting a
deinitprint. - To stop the next one, I'd add a test that releases the owner and asserts the component deallocated too.
A tap inside a deeply nested child view controller must trigger navigation owned several levels up. How do you route it?
- I'd have the child report intent, like
didSelect(item), and leave the navigating to someone else. - Each parent forwards it up until it reaches whoever owns navigation.
- In my default that's a router, so the relay chain stays short and screens never import each other.
- Children never walk the parent hierarchy, which keeps them reusable and testable in isolation.
- The cost is forwarding boilerplate at every level.
- If intent hops through several layers that don't care about it, the navigation owner is in the wrong place.
Two reusable components on one screen both need to be the scroll view's delegate. UIKit allows only one. What do you do?
- I'd keep the screen as the single delegate and have it forward what each component needs, because ownership stays obvious and nothing has to multiplex.
- What would change my mind is components that must work on any screen without wiring.
- Then I'd install a proxy that forwards each call to every target and answers
responds(to:)for any of them, because UIKit only calls methods the delegate says it implements. - Value-returning methods, like
scrollViewShouldScrollToTop(_:), need an explicit winner.
Read it in the app's source
Done with Delegate? Mark it complete. Nailing its cards builds this pumpkin, row by row.