Skip to content

Instantly share code, notes, and snippets.

@almonk
Last active March 27, 2023 07:55
Show Gist options
  • Save almonk/69ddf86532c4d4cd01f77f9cf8254187 to your computer and use it in GitHub Desktop.
Save almonk/69ddf86532c4d4cd01f77f9cf8254187 to your computer and use it in GitHub Desktop.
A little wrapper for NSNotifications with Swift
//
// Notify.swift
//
import Foundation
class Notify {
static let shared = Notify()
func send(event: NSNotification.Name) {
NotificationCenter.default.post(name: event, object: nil, userInfo: nil)
}
func on(event: NSNotification.Name, perform: @escaping () -> Void) {
NotificationCenter.default.addObserver(forName: event, object: nil, queue: nil) { (notification) in
perform()
}
}
}
// Register typesafe events...
extension Notification.Name {
static let updateView = Notification.Name("updateView")
}
// Send an event
Notify.shared.send(event: .updateView)
// Listen to an event
Notify.shared.on(event: .updateView, perform: {
// Do something
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment