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.
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)