Skip to content

Instantly share code, notes, and snippets.

@EkkoG
Forked from pofat/ProtocolNotofication.swift
Created December 15, 2021 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EkkoG/1f37b1f3c5bbe2e5a7763738e8e3ffbe to your computer and use it in GitHub Desktop.
Save EkkoG/1f37b1f3c5bbe2e5a7763738e8e3ffbe to your computer and use it in GitHub Desktop.
Deal with notification with protocol-oriented programing in Swift
//: 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