将内联显式类型注释添加到具有 return 值但在 Swift 中没有输入参数的闭包?
Adding inline explicit type annotations to a closure with a return value but no input parameters in Swift?
通常情况下,函数不需要显式类型,因为它可以从上下文中推断出类型:
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
:“错误:无法推断当前上下文中闭包参数的类型 'Never'”
我能够通过 让它工作,但是如果没有办法使用这种语法为闭包定义一个明确的 return 类型,这看起来很冗长并且像是一个疏忽。
let f = {
1 + 1
} as () -> Double
f()
如果没有输入参数,如何为闭包定义显式 return 类型(使用内联语法而不是 as
)?
注意:如果另一个问题已经存在,我很乐意将其作为重复问题关闭。 (我尝试使用术语 explicit type annotation closure return only
搜索重复项,但找不到任何相关内容。)
空元组()
表示一个空参数列表:
let f = { () -> Double in
1 + 1
}
print(f()) // 2.0
()
可以是 type(与 Void
相同)和该类型的 instance :
let a: Void = ()
let b: () = ()
print(type(of: a) == type(of: b)) // true
通常情况下,函数不需要显式类型,因为它可以从上下文中推断出类型:
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
:“错误:无法推断当前上下文中闭包参数的类型 'Never'”
我能够通过
let f = {
1 + 1
} as () -> Double
f()
如果没有输入参数,如何为闭包定义显式 return 类型(使用内联语法而不是 as
)?
注意:如果另一个问题已经存在,我很乐意将其作为重复问题关闭。 (我尝试使用术语 explicit type annotation closure return only
搜索重复项,但找不到任何相关内容。)
空元组()
表示一个空参数列表:
let f = { () -> Double in
1 + 1
}
print(f()) // 2.0
()
可以是 type(与 Void
相同)和该类型的 instance :
let a: Void = ()
let b: () = ()
print(type(of: a) == type(of: b)) // true