Skip to content

Instantly share code, notes, and snippets.

@leoneparise
Last active October 15, 2018 09:41
Show Gist options
  • Save leoneparise/34ad8fd6c0d5cfc1ff3358aba93edcd4 to your computer and use it in GitHub Desktop.
Save leoneparise/34ad8fd6c0d5cfc1ff3358aba93edcd4 to your computer and use it in GitHub Desktop.
protocol NotificationType {
var name: Notification.Name { get }
static var name: Notification.Name { get }
var userInfo: [AnyHashable : Any] { get }
init?(notification: Notification?)
}
struct Notifications { }
extension NotificationCenter {
func post(_ notification: NotificationType, object: Any? = nil) {
post(name: notification.name, object: object, userInfo: notification.userInfo)
}
func addObserver<T:NotificationType>(forType type: T.Type, object obj: Any? = nil, queue: OperationQueue? = nil, using block: @escaping (T?) -> Swift.Void) -> NSObjectProtocol {
return addObserver(forName: type.name, object: obj, queue: queue) { block( type.init(notification: $0) ) }
}
}
extension Notifications {
struct openUserProfile: NotificationType {
var userId:String
static var name: Notification.Name {
return Notification.Name("LP_openUserProfile")
}
var name:Notification.Name {
return openUserProfile.name
}
var userInfo: [AnyHashable : Any] {
return [ "userId" : userId]
}
init(userId: String) {
self.userId = userId
}
init?(notification: Notification?) {
guard
let name = notification?.name,
let userId = notification?.userInfo?["userId"] as? String,
name == openUserProfile.name
else { return nil }
self.userId = userId
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment