我一直在将项目代码迁移到 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 中,它给了我这些警告和错误。
我知道使用 Void
没有任何意义。如果闭包不包含任何 input arguments and return type
,即闭包可以写成这样:
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”之后变为“无参数”。
关于ios - Swift 4.0 中的空闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579278/