在参数传递时编译Swift 4中的错误

前端之家收集整理的这篇文章主要介绍了在参数传递时编译Swift 4中的错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_0@ 我在 Xcode 9 Beta 3中使用了 3rd party library.我在完成调用中收到以下错误,我无法解决错误
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { 
    self.animationView?.alpha = 0
    self.containerView.alpha  = 1
    completion?()    // -> Error: Missing argument parameter #1 in call.   
}

并在完成功能中获得以下警告:

func openAnimation(_ completion: ((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 '()'?
}
在Swift 4中,元组的处理比以往更加严格.

这种封闭类型:(虚空) – >虚空意味着封闭

>接受一个参数,其类型为Void
>返回Void,意味着不返回任何值

因此,请尝试以下任何一项:

将类型Void的值传递给闭包. (空元组()是Void的唯一实例.)

completion?(())

要不然:

更改参数完成的类型.

func openAnimation(_ completion: (() -> Void)?) {
    //...
}

请记住,即使在Swift 3中,两种类型(Void) – > Void和() – > Void也是不同的.如果您打算表示没有参数的闭包类型,那么后者是合适的.

这个变化是SE-0029 Remove implicit tuple splat behavior from function applications的一部分,据说是在Swift 3中实现的,但似乎Swift 3还没有完全实现它.

在这里,我向您展示了一个简化的检查代码,您可以在Playground上查看差异.

import Foundation

//### Compiles in Swift 3,error and warning in Swift 4
class MyClass3 {

    func openAnimation(_ completion: ((Void) -> Void)?) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {

            completion?()
        }
    }

}

//### Compiles both in Swift 3 & 4
class MyClass4 {

    func openAnimation(_ completion: (() -> Void)?) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {

            completion?()
        }
    }

}
原文链接:https://www.f2er.com/swift/319521.html

猜你在找的Swift相关文章