3 min readMar 4, 2026
SwiftHow to Use NotificationCenter
Broadcast and listen for events in your app.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- 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.
