Swift 4.0 中的空闭包
Empty closures in Swift 4.0
我一直在将我的项目代码迁移到 Swift 4.0。
我遇到了关闭问题。在下面的代码片段中:
class ViewController: UIViewController
{
var completionClosure: ((Void)->(Void))? //WARNING: When calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?
override func viewDidLoad()
{
super.viewDidLoad()
self.completionClosure = { //ERROR: Cannot assign value of type '() -> ()' to type '((Void) -> (Void))?'
print("This is a closure.")
}
}
}
以上代码在 Swift 3.2 中完美运行。在 Swift 4.0 中,它给了我这些警告和错误。
我知道如果闭包不包含任何 input arguments and return type
,那么使用 Void
是没有意义的,即闭包可以这样写:
var completionClosure: (()->())?
但是,为什么它给我错误? Void
和 No Value
不一样吗?
自 Swift 4.0 以来,闭包的概念是否有任何变化?
请注意 Void
只是一个空元组 ()
。
我认为这是由于 Remove implicit tuple splat behavior from function applications (SE-0029)
基本上,此更改表示您不能再将元组作为参数传递。您过去可以通过在函数名称后的 ()
中插入内容来传递参数,或者传递表示参数
的元组
func foo(a: Int, b: Int) {}
let tuple = (a: 1, b: 2)
foo(tuple)
现在你不能。
如果我们将 foo
转换为 swift 4,它看起来像这样:
func foo(a; Int, b: Int) {}
func foo(_ x: (a: Int, b: Int)) {}
所以(Void) -> Void
代表一个接受Void
参数的函数。你过去什么也不能传递,因为 Void
只是一个空元组,在 "splat" 之后变成 "no parameters".
我一直在将我的项目代码迁移到 Swift 4.0。
我遇到了关闭问题。在下面的代码片段中:
class ViewController: UIViewController
{
var completionClosure: ((Void)->(Void))? //WARNING: When calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?
override func viewDidLoad()
{
super.viewDidLoad()
self.completionClosure = { //ERROR: Cannot assign value of type '() -> ()' to type '((Void) -> (Void))?'
print("This is a closure.")
}
}
}
以上代码在 Swift 3.2 中完美运行。在 Swift 4.0 中,它给了我这些警告和错误。
我知道如果闭包不包含任何 input arguments and return type
,那么使用 Void
是没有意义的,即闭包可以这样写:
var completionClosure: (()->())?
但是,为什么它给我错误? Void
和 No Value
不一样吗?
自 Swift 4.0 以来,闭包的概念是否有任何变化?
请注意 Void
只是一个空元组 ()
。
我认为这是由于 Remove implicit tuple splat behavior from function applications (SE-0029)
基本上,此更改表示您不能再将元组作为参数传递。您过去可以通过在函数名称后的 ()
中插入内容来传递参数,或者传递表示参数
func foo(a: Int, b: Int) {}
let tuple = (a: 1, b: 2)
foo(tuple)
现在你不能。
如果我们将 foo
转换为 swift 4,它看起来像这样:
func foo(a; Int, b: Int) {}
func foo(_ x: (a: Int, b: Int)) {}
所以(Void) -> Void
代表一个接受Void
参数的函数。你过去什么也不能传递,因为 Void
只是一个空元组,在 "splat" 之后变成 "no parameters".