Swift 3中带有字符串的参数的responseToSelector/performSelector [英] respondToSelector / performSelector with parameter from a string in Swift 3
本文介绍了Swift 3中带有字符串的参数的responseToSelector/performSelector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须调用类的方法.此方法可能存在或不存在.
我正在寻找2小时后的解决方案.
以下在没有参数sayHello()
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()
我上课了:
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
它不适用于参数!
此外,我尝试使用Swift3 #selector
,但是我找不到从字符串输入方法的方法
Beside, i tried with the Swift3 #selector
, but I found no way to enter a method from a string
推荐答案
Swift方法
func say(something:String)
映射为Objective-C,
is mapped to Objective-C as
- (void)sayWithSomething:(NSString * _Nonnull)something;
,因此正确的选择器应该是
and therefore the correct selector would be
let selectorWithParam = NSSelectorFromString("sayWithSomething:" )
使用#selector
不太容易出错:
let selectorWithParam = #selector(myClass.say(something:))
这篇关于Swift 3中带有字符串的参数的responseToSelector/performSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文