swift3selectornsobjectperformselectorrespond-to

respondToSelector / performSelector with parameter from a string in Swift 3


I have to call method of a class. This method potentially exists or not. I'm looking for a solution from 2 hours. The following works without parameter sayHello()

I have the class :

class myClass: NSObject {
    func say(something:String){
        print("I say : \(something)")
    }

    func sayHello(){
        print("Hello")
    }
}

1st step : Create a selector from a string with a parameter

let selector = NSSelectorFromString("sayHello" ) 
let selectorWithParam = NSSelectorFromString("say:" ) 

2nd step : Test if the method exist

self.bot?.responds(to: selector)// true
self.bot?.responds(to: selectorWithParam) // false        

it doesn't work with a parameter!

Beside, i tried with the Swift3 #selector , but I found no way to enter a method from a string


Solution

  • The Swift method

    func say(something:String)
    

    is mapped to Objective-C as

    - (void)sayWithSomething:(NSString * _Nonnull)something;
    

    and therefore the correct selector would be

    let selectorWithParam = NSSelectorFromString("sayWithSomething:" )
    

    Using #selector is less error-prone:

    let selectorWithParam = #selector(myClass.say(something:))