Last active
          December 7, 2022 21:31 
        
      - 
      
- 
        Save IanKeen/14bba21f84b4ed77fddbd8af00662ccd to your computer and use it in GitHub Desktop. 
    Type safe NotificationCenter
  
        
  
    
      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
    
  
  
    
  | 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) | |
| } | |
| } | |
| } | 
  
    
      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
    
  
  
    
  | 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