当函数具有不同的签名时,将函数作为参数传递

时间:2021-03-04 16:52:12

I red lots of answers but I could not find a definitive answer to my question.

我得到了很多答案,但我无法找到对我的问题的确切答案。

In Swift, I have 3 (or more) different methods. The only thing they have in common is their return type, eg.

在Swift中,我有3种(或更多种)不同的方法。他们唯一的共同点是他们的回归类型,例如。

A(a:String)->MyType
B(a:Int,b:String,c:AnyObject,d:Whatever)->MyType
C(a:Int,b:String,c:Other)->MyType

I need to pass the functions as an argument of a class method, eg.

我需要将函数作为类方法的参数传递,例如。

myClass.configureIOTDevice(configFile:String, functionToCall:A)

Then, inside the body of this method I want to call:

然后,在我想要调用的方法体内:

functionToCall()

As you can see, a problem arises: how to pass the needed arguments for different signatures?

如您所见,出现了一个问题:如何为不同的签名传递所需的参数?

Any help, tip and, why not, rotten tomato is appreciated :-)

任何帮助,提示,为什么不,腐烂的番茄是赞赏:-)

1 个解决方案

#1


0  

You can go like this

你可以这样

func getData( functionToCall : Any) {
    if let function = functionToCall as? ()-> Void {
        function()
    }
    else if let function = functionToCall as? (String, String) -> Int {
        let result = function("a","b")
    }
}

#1


0  

You can go like this

你可以这样

func getData( functionToCall : Any) {
    if let function = functionToCall as? ()-> Void {
        function()
    }
    else if let function = functionToCall as? (String, String) -> Int {
        let result = function("a","b")
    }
}