ios - Swift 4.0 中的空闭包

标签 ios closures void swift4

我一直在将项目代码迁移到 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: (()->())?

但是,为什么它会给我这个错误?不是VoidNo 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/

相关文章:

ios - 将相同的 UITableView 添加到不同的 ViewControllers

iOS - 以编程方式切换 WiFi 网络 - 越狱

delegates - 你能解释一下 lambda 表达式吗?

rust - 在异步移动 block 中返回任何内容

c - (void)var 实际上做了什么?

javascript - 输入新字符后获取 contentEditable div 高度

ios - 自动选择 SwiftUI 中的第 0 个项目

php - ReflectionFunctionAbstract::getClosureThis() 的目的是什么?

c - 如何强制 C 编译器在用 void* 声明时用 long 参数定义函数

c++ - enable_if : minimal example for void member function with no arguments