通常,函数不需要显式类型,因为它可以从上下文推断类型:
let f = { input in
1 + input
}
f(2)
通常您需要提供 explicit type annotation强制它使用特定类型,或者在编译器无法推断类型的情况下。当您有输入参数时,这很简单:let f = { (input: Double) -> Double in
1 + input
}
f(2)
但是,如果您没有输入参数,我不确定语法应该是什么样子:let f = { -> Double in
1 + 1
}
f()
error: Expected expression
我尝试了所有这些变化都无济于事:
let f = { -> Double in
:“错误:预期的表达式”let f = { _ -> Double in
:“错误:无法在当前上下文中推断闭包参数‘_’的类型”,这也将其更改为接受一个参数,这不是我想要的。 let f = { Void -> Double in
:“错误:无法在当前上下文中推断闭包参数‘Void’的类型”let f = { Never -> Double in
:“错误:无法在当前上下文中推断闭包参数“从不”的类型”我可以通过 adding an
as
clause to the end 让它工作,但是如果没有办法使用这种语法为闭包定义明确的返回类型,这似乎很冗长并且像是一种疏忽。let f = {
1 + 1
} as () -> Double
f()
如果没有输入参数,如何为闭包定义显式返回类型(使用内联语法而不是 as
)?注意:如果另一个问题已经存在,我很高兴将其作为重复关闭。 (我尝试使用术语
explicit type annotation closure return only
搜索重复项,但找不到任何相关内容。)
最佳答案
空元组 ()
表示一个空的参数列表:
let f = { () -> Double in
1 + 1
}
print(f()) // 2.0
()
可以是类型(与 Void
相同)和该类型的实例:let a: Void = ()
let b: () = ()
print(type(of: a) == type(of: b)) // true
关于swift - 在 Swift 中向具有返回值但没有输入参数的闭包添加内联显式类型注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65258052/