The observer pattern

Architecture & patterns Mid-level Swift 5.9+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Many unrelated screens must update when the user's subscription status changes. Best approach?

Options
Hint 1 of 1

One change, many listeners.

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

Show answer

Answer: A A shared @Observable store, injected through the environment, that screens read

Correct. Every screen that reads it updates automatically.

Why not the others?
  • B A delegate on the store. Delegates are one-to-one.
  • C Each screen polls a timer. It's wasteful and lags behind.
  • D KVO on a Swift struct. KVO doesn't work on structs.

30-second answer

Observers subscribe to a subject and are told when it changes, so one change reaches many listeners without the subject knowing them. In Swift today that is usually an @Observable model that SwiftUI tracks automatically, withObservationTracking or Observations outside SwiftUI, an AsyncSequence, or Combine publishers. NotificationCenter and KVO remain for system events and Objective-C APIs.

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

Explain the observer pattern in Swift today.

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

  • One-to-many updates
  • @Observable
  • AsyncSequence or Combine
  • Notifications for system events

Deep dive

Observation tracks only properties actually read.

Unsubscribe or cancel to avoid leaks and work on dead objects.

NotificationCenter is global and untyped, so scope it carefully.

KVO works only with NSObject subclasses and @objc dynamic properties.

Common mistakes

  • Using KVO on Swift structs.
  • Polling for changes.

Senior take & follow-ups

Seniors choose the mechanism by scope and type safety.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you observe an @Observable model outside SwiftUI?

    Show hint

    withObservationTracking, or the Observations async sequence (Swift 6.2, iOS 26).

  2. When is NotificationCenter appropriate?

    Show hint

    System events like keyboard or app lifecycle.

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