Search code examples
swiftselectornsresponder

How to update NSResponder selector in swift 2.2


I am implementing a NSControlTextEditingDelegate protocol and I don't know which class/protocol i should match with e.g. commandSelector. #selector(WhichClass.moveUp(_:)) so that the equality will pass.

Currently everything is ok with swift 2.1:

func control(control: NSControl, textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool {

    var goUp = false
    var goDown = false

        if (commandSelector == Selector("moveUp:") ||
        commandSelector == Selector("moveBackward:") ||
        commandSelector == Selector("moveUpAndModifySelection:") ||
        commandSelector == Selector("moveParagraphBackwardAndModifySelection:")
            )

        {
            goUp = true
        }
        if (commandSelector == Selector("moveDown:") ||
        commandSelector == Selector("moveForward:") ||
        commandSelector == Selector("moveDownAndModifySelection:") ||
        commandSelector == Selector("moveParagraphForwardAndModifySelection:")
            ) {
            goDown = true

        }
//...
}

Solution

  • Try this:

    if (commandSelector == #selector(NSResponder.moveUp) ||
    

    You can write it as the following if you prefer:

    if (commandSelector == #selector(NSResponder.moveUp(_:)) ||
    

    In fact, generated Selector instance from #selector does not contain the class info. So, you just find any class defining the same method with the same signature.


    And if you cannot find any class, you can define it in your own protocol and use the protocol name.

    @objc protocol MyProtocol {
        func moveUp(_:AnyObject)
        //...
    }
    

    And use it in #selector:

    if (commandSelector == #selector(MyProtocol.moveUp(_:)) ||
    

    The latter should be the last way, but it actually works.