如何在没有 class 的情况下使用 Swift 2.2 中的#selector 作为第一响应者?

How to use #selector in Swift 2.2 for the first responder, without a class?

我想将 doSomething 发送到 firstResponder,它可以是多个对象中的任何一个。

menuItem = NSMenuItem(title: "Do Something!",
                      action: Selector("doSomething"),
                      keyEquivalent: "")

我在 Swift 2.2 之前使用 Selector("doSomething")。我现在该怎么做?

使用选择器doSomething创建一个协议,并让所有可以成为第一响应者的对象都遵守它。然后为您的 类.

实现选择器
@objc protocol MyProtocol {
    func myCoolFuncThatManyObjectsRespondTo()
}

extension NSObject: MyProtocol {
    func myCoolFuncThatManyObjectsRespondTo() {
        print("Sup?")
    }
}

let menuItem = NSMenuItem(title: "Do Something!", action: #selector(MyProtocol.myCoolFuncThatManyObjectsRespondTo), keyEquivalent: "")
#selector({classname}.{methodname}{signature})

func doSomething() {}

  #selector(MyClass.doSomething)

func doSomething(arg: String) {}

  #selector(MyClass.doSomething(_:))

func doSomething(arg: String, withSomething something: Int) {}

  #selector(MyClass.doSomething(_:withSomething:))

请注意,所选方法必须桥接到 Objective-C,因此 MyClass 应扩展 NSObject 或向方法添加 @objc 注释。