Call a function dynamically in Swift
I am trying to implement a router pattern in Swift and cannot figure out how to call a method dynamically.
For example, there is an array of arguments:
let arguments: [Any] = [100, 0.5, "Test"]
And the handler 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 that it will use as a callback:
let callback: Any = myClass.handler
How do I map the arguments from the above array to the parameters of the function?
I've found that handler argument types can be retrieved using reflection:
reflect(myClass.handler).valueType // upd: or myClass.handler.dynamicType
is
(Swift.Int, Swift.Double, Swift.String) -> ()
I don't know how to iterate through the types of the arguments though or even get their count. I can probably parse this as a string and then use NSInvocation to call the method. Since NSInvocation is not available in Swift, this would require the use of the Objective C helper function. Another drawback is that it will not work with global functions and closures.
Any other ideas are greatly appreciated.
source to share
No one has answered this question yet
Check out similar questions: