1

I want to send doSomething to the firstResponder, which could be any of several objects.

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

I was using Selector("doSomething") prior to Swift 2.2. How do I do it now?

JAL
  • 41,701
  • 23
  • 172
  • 300

2 Answers2

5

Create a protocol with the Selector doSomething and have all of your objects that can be first responders conform to it. Then implement the selector for your classes.

@objc protocol MyProtocol {
    func myCoolFuncThatManyObjectsRespondTo()
}

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

let menuItem = NSMenuItem(title: "Do Something!", action: #selector(MyProtocol.myCoolFuncThatManyObjectsRespondTo), keyEquivalent: "")
JAL
  • 41,701
  • 23
  • 172
  • 300
1
#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:))

Note that the selected method must be bridged to Objective-C, so either MyClass should extend NSObject or add @objc annotation to the method.

szym
  • 5,606
  • 28
  • 34