Skip to content

Instantly share code, notes, and snippets.

@timvermeulen
Last active July 24, 2018 23:15
Show Gist options
  • Save timvermeulen/72843dcd5ec83ef063a1d75ea25f2b51 to your computer and use it in GitHub Desktop.
Save timvermeulen/72843dcd5ec83ef063a1d75ea25f2b51 to your computer and use it in GitHub Desktop.
import Foundation
extension Notification {
struct TypedName<Value> {
let rawValue: String
init(_ rawValue: String) {
self.rawValue = rawValue
}
var notificationName: Name {
return Name(rawValue)
}
}
}
private let userInfoKey = "notificationPayloadUserInfoKey"
extension NotificationCenter {
func addObserver<Value>(
forName name: Notification.TypedName<Value>,
object: Any? = nil,
queue: OperationQueue? = nil,
using block: @escaping (Value) -> Void
) -> NSObjectProtocol {
return addObserver(forName: name.notificationName, object: object, queue: queue) { notification in
let value = notification.userInfo![userInfoKey] as! Value
block(value)
}
}
func post<Value>(_ value: Value, name: Notification.TypedName<Value>, object: Any? = nil) {
self.post(name: name.notificationName, object: object, userInfo: [userInfoKey: value])
}
}
// Example:
extension Notification.TypedName {
static var notificationName: Notification.TypedName<Int> {
return .init("notificationName")
}
}
NotificationCenter.default.addObserver(forName: .notificationName) { int in
// ...
}
NotificationCenter.default.post(123, name: .notificationName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment