How do you create custom notifications in Swift 3?

前端 未结 13 580
自闭症患者
自闭症患者 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)
    
    0 讨论(0)
  • 2020-12-04 09:14

    if you use string-only custom notifications, there's no reason to extend any classes but String

        extension String {
            var notificationName : Notification.Name{
                return Notification.Name.init(self)
            }
        }
    
    0 讨论(0)
  • 2020-12-04 09:16

    I may suggest another option which is similar to what @CesarVarela suggested.

    extension Notification.Name {
        static var notificationName: Notification.Name {
            return .init("notificationName")
        }
    }
    

    This will let you post and subscribe on notifications easily.

    NotificationCenter.default.post(Notification(name: .notificationName))
    

    Hope this will help you.

    0 讨论(0)
  • 2020-12-04 09:18
    NSNotification.Name(rawValue: "myNotificationName")
    
    0 讨论(0)
  • 2020-12-04 09:24

    You could also use a protocol for this

    protocol NotificationName {
        var name: Notification.Name { get }
    }
    
    extension RawRepresentable where RawValue == String, Self: NotificationName {
        var name: Notification.Name {
            get {
                return Notification.Name(self.rawValue)
            }
        }
    }
    

    And then define your notification names as an enum anywhere you want. For example:

    class MyClass {
        enum Notifications: String, NotificationName {
            case myNotification
        }
    }
    

    And use it like

    NotificationCenter.default.post(name: Notifications.myNotification.name, object: nil)
    

    This way the notification names will be decoupled from the Foundation Notification.Name. And you will only have to modify your protocol in case the implementation for Notification.Name changes.

    0 讨论(0)
  • 2020-12-04 09:24

    There is a cleaner (I think) way to achieve it

    extension Notification.Name {
    
        static let onSelectedSkin = Notification.Name("on-selected-skin")
    }
    

    And then you can use it like this

    NotificationCenter.default.post(name: .onSelectedSkin, object: selectedSkin)
    
    0 讨论(0)
提交回复
热议问题