How do you create custom notifications in Swift 3?

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

    Notification.post is defined as:

    public func post(name aName: NSNotification.Name, object anObject: AnyObject?)
    

    In Objective-C, the notification name is a plain NSString. In Swift, it's defined as NSNotification.Name.

    NSNotification.Name is defined as:

    public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
        public init(_ rawValue: String)
        public init(rawValue: String)
    }
    

    This is kind of weird, since I would expect it to be an Enum, and not some custom struct with seemingly no more benefit.

    There is a typealias in Notification for NSNotification.Name:

    public typealias Name = NSNotification.Name
    

    The confusing part is that both Notification and NSNotification exist in Swift

    So in order to define your own custom notification, do somethine like:

    public class MyClass {
        static let myNotification = Notification.Name("myNotification")
    }
    

    Then to call it:

    NotificationCenter.default().post(name: MyClass.myNotification, object: self)
    

提交回复
热议问题