The delegate pattern

Architecture & patterns Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A custom picker needs its owner to supply the row count, each row's title, and to hear about selection. Which pattern?

Options
Hint 1 of 1

How many related callbacks are there?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A weak delegate or data source protocol

Correct. It's one owner and several related callbacks.

Why not the others?
  • B A single closure. One closure can't cleanly answer several different questions.
  • C NotificationCenter. It's one-to-many and untyped, and can't return values.
  • D Subclass the picker for every use. That couples behaviour to inheritance.

30-second answer

A delegate is an object that another object calls through a protocol to ask questions or report events, like UITableViewDelegate. It suits one-to-one communication with several related callbacks. Declare the protocol AnyObject and the property weak to avoid retain cycles. For a single callback a closure is lighter; for many listeners, use observation.

Practise saying it · 30 s. No recording, just a timer

Explain the delegate pattern.

Say your answer out loud, then check which of these points you covered:

  • One-to-one protocol
  • Weak, AnyObject
  • Closure for single callbacks

Deep dive

Data sources are delegates that supply data.

Protocol extensions can provide default implementations for optional methods.

Delegate methods usually pass the sender as the first parameter.

Async/await replaces delegates for single-result callbacks.

Common mistakes

  • Strong delegate references.
  • Delegates for one-to-many broadcasts.

Senior take & follow-ups

Seniors pick delegates for one-to-one, multi-callback relationships and keep them weak.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why pass the sender?

    Show hint

    One delegate can serve several instances.

  2. Delegate or closure?

    Show hint

    Delegate for a group of callbacks, closure for one.

Suggest a fix if something here is wrong or out of date.