Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active December 7, 2022 21:31
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IanKeen/14bba21f84b4ed77fddbd8af00662ccd to your computer and use it in GitHub Desktop.
Save IanKeen/14bba21f84b4ed77fddbd8af00662ccd to your computer and use it in GitHub Desktop.
Type safe NotificationCenter
struct Notification<T> {
let name: NSNotification.Name
}
private let notificationData = "_notificationData"
extension NotificationCenter {
func post<T>(_ notification: Notification<T>, object: Any? = nil, data: T) {
post(name: notification.name, object: object, userInfo: [notificationData: data])
}
func addObserver<T>(for notification: Notification<T>, object obj: Any? = nil, queue: OperationQueue? = .main, using block: @escaping (T) -> Void) -> NSObjectProtocol {
return addObserver(forName: notification.name, object: obj, queue: queue) { n in
block(n.userInfo![notificationData] as! T)
}
}
}
enum Foo {
case int(Int)
case str(String)
}
extension Notification {
static var foo: Notification<Foo> { return .init(name: .init(#function)) }
}
let x = NotificationCenter.default.addObserver(for: .foo) { foo in
print(foo)
}
NotificationCenter.default.post(.foo, data: .int(1))
NotificationCenter.default.post(.foo, data: .str("wooo"))
NotificationCenter.default.post(.foo, data: .int(42))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment