Mediator 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
- ✓Mediator Pattern runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓NotificationCenter is the Foundation mediator and has been since NeXTSTEP: post a Notification with a name and a userInfo dictionary, and observers receive it.
- ✓Prefer a Combine subject or an AsyncStream over NotificationCenter in new code, because the payload is typed and the subscription returns a cancellable whose lifetime you control.
- ✓The Swift trap: The two NotificationCenter observer APIs have different memory rules and mixing them is the classic bug.
- ✓NotificationCenter posts synchronously on the posting thread and looks observers up by name in a hash table, so dispatch is fast and the cost is the observers themselves; posting from a background thread means observers run there, which is the usual cause of a UI update off the main thread.
What Mediator Pattern actually is
Mediator Pattern in Swift: what you actually reach for
Swift implementation
import Foundation
import Combine
final class Hub {
// Typed hub: no userInfo dictionary, no string names.
let saved = PassthroughSubject<String, Never>()
}
final class Screen {
private var bag = Set<AnyCancellable>()
init(hub: Hub) {
hub.saved
.receive(on: DispatchQueue.main)
.sink { [weak self] id in self?.render(id) } // weak: no retain cycle
.store(in: &bag) // torn down with self
}
func render(_ id: String) {}
}
final class LegacyScreen {
// BLOCK-based observers are NOT auto-removed: keep the token or this leaks.
private var token: NSObjectProtocol?
init() {
token = NotificationCenter.default.addObserver(
forName: .init("saved"), object: nil, queue: .main) { _ in }
}
deinit {
if let token { NotificationCenter.default.removeObserver(token) }
}
// Selector-based observers HAVE been auto-removed since iOS 9 / macOS 10.11.
}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 Mediator Pattern?
NotificationCenter is the Foundation mediator and has been since NeXTSTEP: post a Notification with a name and a userInfo dictionary, and observers receive it. Combine adds typed publishers, with PassthroughSubject as a hub carrying a declared Output and Failure type, which removes the untyped dictionary. Since Swift 5.5 an AsyncStream turns any of these into an async sequence consumable with for-await-in, and the Observation framework in Swift 5.9 covers the property-observation case directly.
What is the most common Swift mistake when implementing Mediator Pattern?
The two NotificationCenter observer APIs have different memory rules and mixing them is the classic bug. Selector-based observers registered with addObserver(_:selector:name:object:) have been removed automatically on deallocation since iOS 9 and macOS 10.11, so the old removeObserver in deinit is unnecessary. Block-based observers registered with addObserver(forName:object:queue:using:) are NOT: the center retains the block, the block usually captures self, and neither is released until you call removeObserver with the returned token. So the API that looks more modern is the one that leaks if you ignore its return value.
How does Mediator Pattern actually perform in Swift?
NotificationCenter posts synchronously on the posting thread and looks observers up by name in a hash table, so dispatch is fast and the cost is the observers themselves; posting from a background thread means observers run there, which is the usual cause of a UI update off the main thread. Combine adds allocation per subscription and per value for the publisher chain, which is measurable in a hot stream. AsyncStream buffers according to its declared policy, and an unbounded buffer with a slow consumer grows without limit. 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 trialStudying for this? Devin free tiers and academic plans are laid out 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.