Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
//: Playground - noun: a place where people can play
import Cocoa
// I’m trying to figure out how to add a Notification observer in Swift code where the notification name is defined in a .m file.
// This playground won’t actually run, because it assumes an NSString named SomeNotification defined in a .m file. So it can’t actually be used to see the errors. It’s just for illustration.
// The errors are listed in the comments.
class MyClass {
override init() {
// Error: Cannot invoke value of type 'Notification.Name.Type' (aka 'NSNotification.Name.Type') with argument list '(rawValue: NSNotification.Name)'
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: Notification.Name(rawValue: SomeNotification), object: nil)
// Error: Cannot convert value of type 'NSNotification.Name' to type 'String' in coercion.
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: Notification.Name(rawValue: SomeNotification as String), object: nil)
// Error: Type 'NSNotification.Name?' has no member 'SomeNotification'
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: .SomeNotification, object: nil)
dynamic func somethingHappened(_ notification: Notification) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.