Dynamically call a function in Swift

℡╲_俬逩灬. 提交于 2021-02-19 03:37:05

问题


I’m trying to implement a router pattern in Swift and can’t figure out how to dynamically call a method.

For example, there’s an array of arguments:

let arguments: [Any] = [100, 0.5, "Test"]

And a handler which needs to be called:

public class MyClass {
    public func handler(value1: Int, value2: Double, text: String) {
        print("int=\(value1), double=\(value2), string=\(text)")
    }
}
let myClass = MyClass()

The router has an untyped function reference which it will use as a callback:

let callback: Any = myClass.handler

How do I map the arguments from the array above to the function parameters?

I’ve found that handler’s argument types can be obtained via reflection:

reflect(myClass.handler).valueType // upd: or myClass.handler.dynamicType
is
(Swift.Int, Swift.Double, Swift.String) -> ()

I don’t know how to iterate argument types though or even get their count. Probably I can parse this as a string then use NSInvocation to call the method. As NSInvocation is not available in Swift, this will require using an Objective C helper function. Another downside is that it won’t work with global functions and closures.

Any other ideas are very welcome.

来源:https://stackoverflow.com/questions/31712803/dynamically-call-a-function-in-swift

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