SwiftPumpkin

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

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

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 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

Done with Delegate? Mark it complete. Nailing its cards builds this pumpkin, row by row.