iosswift3notificationsextension-methodsnsnotifications

How to use Notification.Name extension from Swift to Objective-C?


I created an extension for Notification.Name as below:

public extension Notification.Name {
    public static let blahblahblah = Notification.Name(rawValue: "blahblahblah")
}

Now I want to use this extension in Objective-C, but it's not accessible even if its public.

How can I access and use this Swift extension in both Objective-C and Swift?

Previously I was using constant values in Objective-C, but now I'm upgrading my code and want to use this extension.


Solution

  • Notification.Name doesn't exist in Objective-C. And the Objective-C type NotificationName is really just an NSString. To use Swift stuff in Objective-C, the class must be available in both, and can't be a Swift struct (like Notification or String, say).

    To do what you want, then, you need to have two extensions:

    1) Add an Objective-C-compatible object extension to your Swift file:

    public extension NSNotification {
        public static let blahblahblah: NSString = "blahblahblah"
    }
    

    Note: in Swift 4, properties must be computed for Objective-C compatibility. That would look like:

    @objc public extension NSNotification {
        public static var blahblahblah: NSString {
            return "blahblahblah"
        }
    }
    

    Note the var in the computed property: computed properties can't be immutable, so can't use let.

    2) In the Objective-C file, import Xcode's generated Swift header file (below any other imports):

    #import "YourProjectName-Swift.h"
    

    Note: replace YourProjectName with the actual name of your project. So, if your project is named "CoolGameApp", the Swift header would be "CoolGameApp-Swift.h". If your project name has spaces, like "Cool Game App", replace them with dashes: "Cool-Game-App-Swift.h"

    3) Rebuild the project.

    Now, you should be able to access the extension in Objective-C:

    [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.blahblahblah object:self];