-
-
Save EkkoG/1f37b1f3c5bbe2e5a7763738e8e3ffbe to your computer and use it in GitHub Desktop.
Deal with notification with protocol-oriented programing in Swift
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import UIKit | |
// This is for dmoe, you can use a generice type to limit your observer to an UIViewController for common usage. | |
typealias NotifiableExecuteBlock = (Notification) -> Void | |
protocol Notifiable { | |
var name: Notification.Name { get } | |
func observe(by observer: Any, withSelector selector: Selector, object: Any?) | |
func observe(with object: Any?, using block: @escaping NotifiableExecuteBlock) | |
func post(object: Any? ,userInfo: [AnyHashable: Any]?) | |
static func remove(observer: Any) | |
} | |
extension Notifiable { | |
func observe(by observer: Any, withSelector selector: Selector, object: Any? = nil) { | |
NotificationCenter.default.addObserver(observer, selector: selector, name: name, object: object) | |
} | |
func observe(with object: Any?, using block: @escaping NotifiableExecuteBlock) { | |
NotificationCenter.default.addObserver(forName: name, object: object, queue: nil, using: block) | |
} | |
func post(object: Any? = nil, userInfo: [AnyHashable: Any]? = nil) { | |
NotificationCenter.default.post(name: name, object: object, userInfo: userInfo) | |
} | |
static func remove(observer: Any) { | |
NotificationCenter.default.removeObserver(observer) | |
} | |
} | |
extension Notification.Name: Notifiable { | |
var name: Notification.Name { | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment