gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:05 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com