Replace Stringly Typed Notifications With Swift Messages

Ever opened a notification handler and found three optional casts before the actual work starts?

guard let bookID = notification.userInfo?["bookID"] as? UUID,
    let title = notification.userInfo?["title"] as? String
else {
    return
}

The sender knows those values. The receiver knows those values. Somehow the agreement between them still depends on two strings and a dictionary of Any.

Foundation’s typed notification messages let us put that agreement in a Swift type. They also make the delivery isolation explicit. Let’s migrate one event in a library app without rebuilding the app around an event bus.

The APIs below require iOS 26 or macOS 26. September 2026 review: the complete example was compiled in Swift 6 mode with Xcode 27, and its delivery and lifetime checks ran on macOS 27.

Give the event a real payload

Our editor renames a book. A separate library summary needs to learn about the successful change. Both features belong to one LibrarySession, so that session makes a useful subject:

import Foundation

@MainActor
final class LibrarySession {}

struct BookRenamed: NotificationCenter.MainActorMessage {
    typealias Subject = LibrarySession

    let bookID: UUID
    let title: String
}

The subject answers “which library?” The payload answers “which book changed, and what is its new title?” Keeping those separate becomes useful when two windows show different libraries.

For this Swift-only event, the message type is enough. We do not need to invent a notification name or a userInfo representation. Apple’s notification message guide explains the two available contracts: MainActorMessage for main-actor delivery, and AsyncMessage for asynchronous delivery with a sendable payload.

Choose the contract the feature needs. A UI-owned library event is a good fit for MainActorMessage. A background importer should not become main-actor isolated merely to reuse this particular message.

Let the owner keep the observation alive

Here is the summary object. I’m injecting the notification center because it makes both the dependency and the tests much easier to understand.

@MainActor
final class LibrarySummary {
    private let center: NotificationCenter
    private let session: LibrarySession
    private var token: NotificationCenter.ObservationToken?

    private(set) var titles: [UUID: String] = [:]

    init(center: NotificationCenter, session: LibrarySession) {
        self.center = center
        self.session = session
    }

    func start() {
        guard token == nil else { return }

        token = center.addObserver(of: session, for: BookRenamed.self) {
            [weak self] message in
            self?.titles[message.bookID] = message.title
        }
    }

    func stop() {
        token = nil
    }
}

Three details are doing useful work here.

First, the token is a property. If we only create a local token inside start(), observation ends when that token’s lifetime ends. The new ObservationToken manages deregistration when its last retained copy goes away. It is different from the older block-observer token pattern many of us have memorized.

Second, repeated calls to start() do not register repeated handlers. SwiftUI can show and hide the same feature several times; that should not multiply its event processing.

Third, the callback captures the summary weakly. Keeping the token on the observer owner should not also make the registration keep that owner alive indefinitely. stop() drops our only token copy, so this example’s observation ends immediately. If your code shares token copies, use center.removeObserver(token) when you need explicit removal regardless of those copies.

The example uses a plain class to keep the notification mechanics visible. In a SwiftUI app, the summary can be an @Observable model owned by the feature. Start and stop observation at that owner’s intended lifetime, rather than adding a new observer every time body runs.

Post after committing the change

Posting uses the same session instance we used when registering:

@MainActor
func announceRename(
    bookID: UUID,
    savedTitle: String,
    session: LibrarySession,
    center: NotificationCenter
) {
    center.post(
        BookRenamed(bookID: bookID, title: savedTitle),
        subject: session
    )
}

Call that after the store accepts the rename. If the disk write fails, we should not tell the rest of the app that the new title was saved.

This also avoids making observers responsible for completing the original command. The editor asks the store to rename a book and handles that result. The notification announces the result to interested features. That ordering makes a failed save straightforward to explain to the user.

The accepted concurrency-safe notifications proposal specifies synchronous main-actor delivery for this message flavor. By the time post returns, these synchronous handlers have run. That is convenient, but it also means a slow handler delays the poster. Keep the callback small, and be careful about posting another event from inside it: nested event handling can make state changes harder to follow.

Test the boundary with a private center

We can exercise the important behavior without a global notification center, a network call, or a sleep:

@MainActor
func checkObservation() {
    let center = NotificationCenter()
    let session = LibrarySession()
    let otherSession = LibrarySession()
    let summary = LibrarySummary(center: center, session: session)
    let id = UUID()

    summary.start()
    center.post(
        BookRenamed(bookID: id, title: "Working title"),
        subject: session)
    assert(summary.titles[id] == "Working title")

    center.post(
        BookRenamed(bookID: id, title: "Wrong library"),
        subject: otherSession)
    assert(summary.titles[id] == "Working title")

    summary.stop()
    center.post(
        BookRenamed(bookID: id, title: "After stop"),
        subject: session)
    assert(summary.titles[id] == "Working title")
}

The second assertion catches a particularly easy mistake: accidentally observing every library when the feature only owns one. I also check stop-then-start behavior in the complete example, because navigation often exposes lifecycle bugs before anything else does.

A message is still an event

Typed notifications do not replay the current library when a screen opens. The summary still needs an initial snapshot from the store. For synchronous main-actor state, register and read that snapshot in the same uninterrupted operation. For an asynchronous initial load, decide how to reconcile events that arrive while the snapshot is loading; stronger payload types do not solve that race for us.

Likewise, notifications are not a durable queue. A feature that must upload every pending edit needs persistent work tracking. A feature that only needs to refresh an already visible title may need nothing more than this message.

If an older Objective-C sender or observer must participate, add the documented conversion methods and a shared notification name, then test both directions. Migrate one event at a time. For a Swift-only feature, start with the small typed version above and let the compiler replace those defensive dictionary casts.