respondToSelector / performSelector with parameter from a string in Swift 3

 ̄綄美尐妖づ 提交于 2020-01-05 03:37:34

问题


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


回答1:


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:))


来源:https://stackoverflow.com/questions/41020999/respondtoselector-performselector-with-parameter-from-a-string-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!