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:
- one for the Swift
Notification.Name
, as you have; and,
- one for an Objective-C object (
NSString
, say, or perhaps NSNotification
if you prefer).
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];
@objc
, but it can only be used with members of classes and protocols, not for extensions. Thanks @Leyden – Unwept