swift - 无法将类型 '()' 的值转换为预期的参数类型 '() -> ()'

标签 swift

我想在 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/

相关文章:

ios - 包装在 UIViewController 中的 UICollectionView

ios - Swift 2.1 错误排序到位,仅在发布版本上

ios - 如何使 [load on scroll] 不继续将图像添加到 ram?

Swift 从 WebView 调用电话

ios - 如何快速保存 Json 数据并离线显示

swift - 使用 Alamofire 将多个类型参数发送到 API - Swift

ios - fatal error 索引超出范围 swift 3 SpriteKit

Swift:实例化符合协议(protocol)的类(AnyClass)

swift - 从具有 uint8_t ** 作为输出参数的 Swift 调用 native 方法

swift - 从函数返回后无法在 Swift 2 中更改字符串数组