How do you create custom notifications in Swift 3?

前端 未结 13 745
自闭症患者
自闭症患者 2020-12-04 09:07

In Objective-C, a custom notification is just a plain NSString, but it\'s not obvious in the WWDC version of Swift 3 just what it should be.

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 09:29

    The advantage of using enums is that we get the compiler to check that the name is correct. Reduces potential issues and makes refactoring easier.

    For those who like using enums instead of quoted strings for notification names, this code does the trick:

    enum MyNotification: String {
        case somethingHappened
        case somethingElseHappened
        case anotherNotification
        case oneMore
    }
    
    extension NotificationCenter {
        func add(observer: Any, selector: Selector, 
                 notification: MyNotification, object: Any? = nil) {
            addObserver(observer, selector: selector, 
                        name: Notification.Name(notification.rawValue),
                        object: object)
        }
        func post(notification: MyNotification, 
                  object: Any? = nil, userInfo: [AnyHashable: Any]? = nil) {
            post(name: NSNotification.Name(rawValue: notification.rawValue), 
                 object: object, userInfo: userInfo)
        }
    }
    

    Then you can use it like this:

    NotificationCenter.default.post(.somethingHappened)
    

    Though unrelated to the question, the same can be done with storyboard segues, to avoid typing quoted strings:

    enum StoryboardSegue: String {
        case toHere
        case toThere
        case unwindToX
    }
    
    extension UIViewController {
        func perform(segue: StoryboardSegue) {
            performSegue(withIdentifier: segue.rawValue, sender: self)
        }
    }
    

    Then, on your view controller, call it like:

    perform(segue: .unwindToX)
    

提交回复
热议问题