【问题标题】:Empty closures in Swift 4.0 [duplicate]Swift 4.0 中的空闭包 [重复]
【发布时间】:2018-03-16 16:45:26
【问题描述】:

我一直在将我的项目代码迁移到 Swift 4.0

我遇到了关闭问题。在下面的代码sn-p中:

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: (()->())?

但是,为什么它给了我错误? VoidNo Value不一样吗?

Swift 4.0 以来,闭包的概念有什么变化吗?

【问题讨论】:

标签: ios closures void swift4


【解决方案1】:

注意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”之后变成“无参数”。

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多