MasterOnce
HomeBlogHow-To
3 min readMar 4, 2026
Swift

How to Use NotificationCenter

Broadcast and listen for events in your app.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. Adjust the inputs to match your use case.

Copy and paste

import Foundation

let name = Notification.Name("DemoEvent")

let observer = NotificationCenter.default.addObserver(
    forName: name,
    object: nil,
    queue: .main
) { notification in
    print("Received", notification.name.rawValue)
}

NotificationCenter.default.post(name: name, object: nil)
NotificationCenter.default.removeObserver(observer)

Notes

  • Keep functions small and focused for reuse.
  • Prefer safe APIs like optionals and guards.