我想在 Swift 中将函数作为参数传递。为此,我将采用回调参数的函数定义为:
func foo(callback: () -> () = { _ in }) { callback() }
然后我定义了另一个我将使用的函数:
func toBeCalled() -> () {
print("hello world")
}
foo(toBeCalled())
我收到以下错误:
Cannot convert value of type '()' to expected argument type '() -> ()'
有没有人遇到过这个问题?我尝试了多种方法,包括使用 Void。
谢谢!
最佳答案
您必须传递函数而不是该函数的结果:
foo(toBeCalled)
toBeCalled
的类型为 () -> ()
但是当您编写 toBeCalled()
时,该函数将被执行并获得返回值输入 ()
。
关于swift - 无法将类型 '()' 的值转换为预期的参数类型 '() -> ()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36987556/