How do you create custom notifications in Swift 3?

前端 未结 13 732
自闭症患者
自闭症患者 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:13

    You can add a custom initializer to NSNotification.Name

    extension NSNotification.Name {
        enum Notifications: String {
            case foo, bar
        }
        init(_ value: Notifications) {
            self = NSNotification.Name(value.rawValue)
        }
    }
    

    Usage:

    NotificationCenter.default.post(name: Notification.Name(.foo), object: nil)
    

提交回复
热议问题