在 ObjC 中,您可以简单地使用NSObject
.
[Machine performSelector:@selector(calculate:) withObject:num];
但是你如何在 Swift 2.2 中做到这一点?
@objc(Machine) // put it here, so you can simply copy/paste into Playground
class Machine: NSObject {
static func calculate(param: NSNumber) -> String {
if param.integerValue > 5 {
return "42"
}
return "42" // there is only 1 answer to all the questions :D
}
}
if let aClass = NSClassFromString("Machine") {
let sel = #selector(Machine.calculate(_:))
let num = NSNumber(integer: 1337)
let answer = aClass.performSelector(sel, withObject: num) // compiler error
// let answer = aClass.calculate(num) // <-- this works
print(answer)
}
使用此代码,我收到以下编译器错误:
错误:无法使用类型为“(Selector,withObject:NSNumber)”的参数列表调用“performSelector”
我在这里想念什么?