Last active
March 27, 2023 07:55
-
-
Save almonk/69ddf86532c4d4cd01f77f9cf8254187 to your computer and use it in GitHub Desktop.
A little wrapper for NSNotifications with Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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