mercredi 29 juillet 2015

Dynamically call a function in Swift

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
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.





Aucun commentaire:

Enregistrer un commentaire