我想要创建一个函数(函数A),它的参数是具有多个参数的函数(函数B)。
因此,函数(B)可以有0,1或更多的参数,在函数(A)中,我想根据B函数参数的数量和类型来做不同的事情。
我认为这是可以通过反思实现的,但在Swift中有可能吗?
编辑:1,让我们考虑我想要支持的函数B的三种情况:
func functionB() {
print(“HelloWorld”)
}
func functionB(a: Int) {
print(“HelloWorld1”)
}
func functionB(a: Int, b:String) -> Int {
print(“HelloWorld2”)
return 2
}我希望独立于函数B的签名方法,在函数A中执行不同的任务,该函数以函数B为参数。
func functionA(function: I don’t know how to pass the different cases of the function B as a parameter...generic types?) {
if function.args = 0 {
print(“First example”)
}
if function.firstParameter.self is Int.Type {
print(“second Example”)
}
etc...我想实现这一点,以便处理具有相同功能的不同签名方法。
编辑2:很抱歉之前没有指定它,但我无法访问函数B。我必须在运行时(而不是构建时)计算。这两个函数在一个单独的包中。其目的是,应用程序必须在运行时动态地执行不同的任务,只知道方法的签名,特别是参数类型。
发布于 2020-04-17 03:34:30
超负荷。
func functionA(functionB: () -> Void) { functionB() }
func functionA(functionB: (Int) -> Void) { functionB(0) }
func functionA(functionB: (Int, String) -> Int) { functionB(0, "") }
functionA(functionB: functionB as () -> Void)
functionA( functionB: functionB(a:) )
functionA( functionB: functionB(a:b:) )发布于 2020-04-16 22:35:08
正如注释中所建议的那样,您可以使用Any
func functionA(f: Any, a: Int?, b: String?) {
if let f = f as? () -> Void {
f()
} else if let f = f as? (Int) -> Void , let a = a {
f(a)
} else if let f = f as? (Int, String) -> Int, let a = a, let b = b {
let result = f(a, b)
print(result)
} else {
print("f is not a valid object")
}
}
func functionB(a: Int, b: String) -> Int {
print(a, b)
return 3
}
functionA(f: functionB, a: 42, b: "Hello world")https://stackoverflow.com/questions/61260655
复制相似问题