Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift中动态调用函数_Swift_Reflection_Performselector_Nsinvocation - Fatal编程技术网

在Swift中动态调用函数

在Swift中动态调用函数,swift,reflection,performselector,nsinvocation,Swift,Reflection,Performselector,Nsinvocation,我试图在Swift中实现路由器模式,但不知道如何动态调用方法 例如,有一组参数: let arguments: [Any] = [100, 0.5, "Test"] 以及需要调用的处理程序: public class MyClass { public func handler(value1: Int, value2: Double, text: String) { print("int=\(value1), double=\(value2), string=\(text

我试图在Swift中实现路由器模式,但不知道如何动态调用方法

例如,有一组参数:

let arguments: [Any] = [100, 0.5, "Test"]
以及需要调用的处理程序:

public class MyClass {
    public func handler(value1: Int, value2: Double, text: String) {
        print("int=\(value1), double=\(value2), string=\(text)")
    }
}
let myClass = MyClass()
路由器有一个非类型化的函数引用,它将用作回调:

let callback: Any = myClass.handler
如何将上面数组中的参数映射到函数参数

我发现handler的参数类型可以通过反射获得:

reflect(myClass.handler).valueType // upd: or myClass.handler.dynamicType
is
(Swift.Int, Swift.Double, Swift.String) -> ()
我不知道如何迭代参数类型,甚至不知道如何获得它们的计数。可能我可以将其解析为字符串,然后使用NSInvocation调用该方法。由于NSInvocation在Swift中不可用,因此需要使用目标C辅助函数。另一个缺点是它不能与全局函数和闭包一起工作


任何其他想法都非常受欢迎。

您如何知道参数的数量和类型与函数的参数匹配?@newacct,如果不匹配,则在运行时会失败。它的用法如下:router.addPath([“commandName”,captureWord(“parameterName”)],handlerFunction)。在这种情况下,HandlerFunction应接受字符串。用于试验的快捷方式: