Observer Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Observer Pattern runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Swift has moved through three generations and all three are still in the field. NotificationCenter is the old string-keyed global bus.
- ✓On iOS 17 and newer, annotate the model with @Observable and let SwiftUI track exactly the properties a view actually reads, no publisher, no cancellable, and far fewer redundant redraws than ObservableObject, which invalidates on ANY published change.
- ✓The Swift trap: The single most common Combine bug is discarding the AnyCancellable that sink returns: the subscription is cancelled the instant the token deallocates, so the pipeline silently never fires and there is no warning, store it in a cancellables set.
- ✓Combine carries real per-event overhead: each value travels through a chain of allocated subscriber boxes with existential dispatch, so a very high-frequency publisher is far slower than a direct closure call.
What Observer Pattern actually is
Observer Pattern in Swift: what you actually reach for
Swift implementation
import Foundation
import Combine
import Observation
// iOS 17+ / Swift 5.9+: the current answer. Per-property read tracking.
@Observable
final class Counter {
var value: Int = 0
// No @Published, no ObservableObject, no AnyCancellable.
// A view that never reads 'value' is never invalidated by it.
}
// Combine, where you still need a stream:
final class LegacyCounter: ObservableObject {
@Published var value: Int = 0
}
final class Watcher {
// MUST be stored: an AnyCancellable that deallocates cancels the
// subscription instantly and the sink silently never fires.
private var cancellables = Set<AnyCancellable>()
func observe(_ counter: LegacyCounter) {
counter.$value
.removeDuplicates()
.sink { [weak self] v in // [weak self] or you leak the graph
self?.handle(v)
}
.store(in: &cancellables)
}
private func handle(_ v: Int) { print(v) }
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Observer Pattern?
Swift has moved through three generations and all three are still in the field. NotificationCenter is the old string-keyed global bus. Combine (2019) gives ObservableObject, the @Published property wrapper, PassthroughSubject and CurrentValueSubject, with AnyCancellable as the subscription token. The current answer for SwiftUI is the Observation framework introduced with Swift 5.9 and iOS 17: the @Observable macro replaces ObservableObject and @Published entirely and tracks reads at the property level.
What is the most common Swift mistake when implementing Observer Pattern?
The single most common Combine bug is discarding the AnyCancellable that sink returns: the subscription is cancelled the instant the token deallocates, so the pipeline silently never fires and there is no warning, store it in a cancellables set. The second is a retain cycle from a sink closure that strongly captures self while self owns the cancellable, which leaks the whole object graph; [weak self] in the closure is mandatory. With @Observable, the analogous surprise is that only properties READ during body are tracked, so a view that reads a value inside a Task or a callback will not re-render when it changes.
How does Observer Pattern actually perform in Swift?
Combine carries real per-event overhead: each value travels through a chain of allocated subscriber boxes with existential dispatch, so a very high-frequency publisher is far slower than a direct closure call. @Observable is cheaper for UI because tracking is per-property, so mutating a field no view reads triggers zero invalidations, whereas ObservableObject re-renders every observing view on any @Published write. NotificationCenter is the slowest of the three (string lookup plus userInfo dictionary boxing) and should not be on a hot path. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.