SwiftPumpkin

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

Sets delegatedidPick(_:)ConformsOwnerConforms to protocolDelegating objectweak var delegateDelegate protocolAnyObject
calls or tellsreports backOne-to-one callbacks through a protocol, held weakly to avoid a retain cycle.
  • The picker defines PumpkinPickerDelegate.
  • Its owner conforms and receives didPick.
  • The picker never knows its owner's type.
PartOwnsLooks like
Delegating objectAsk or tell its delegateweak var delegate
ProtocolThe conversation's contractprotocol PumpkinPickerDelegate: AnyObject
OwnerConforms and answersParent 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 callbacksDelegate, UIKit style.
One callbackA closure.
BroadcastsPub/sub or an observable model.

Compared

Delegate vs closure vs pub/sub

DelegateClosurePub/sub
ListenersOneOneMany
Several related eventsNaturalOne closure eachEvent enum
Retain-cycle riskIf not weakCapture listsToken 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.

30-second answer

Explain Delegate in 30 seconds.

SwiftAsked directly

Delegate protocol or closures: how do you choose for a component's callbacks in Swift?

iOS codingAsked indirectly

After adding a delegate to your custom component, neither the component nor its owning screen ever deallocates. What happened?

iOS codingAsked indirectly

A tap inside a deeply nested child view controller must trigger navigation owned several levels up. How do you route it?

iOS codingAsked indirectly

Two reusable components on one screen both need to be the scroll view's delegate. UIKit allows only one. What do you do?

Read it in the app's source