参数传递时Swift 4中的编译错误 [英] Compile error in Swift 4 on parameter passing

查看:101
本文介绍了参数传递时Swift 4中的编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Xcode 9 Beta 3中使用了第三方库,并且出现了以下错误在完成通话中,我无法解决此错误:

I used 3rd party library in Xcode 9 Beta 3. And I am getting the following error in the completion call, I am not able to resolve this error:

DispatchQueue.main.asyncAfter(deadline: .now() + delay) { 
    self.animationView?.alpha = 0
    self.containerView.alpha  = 1
    completion?()    // -> Error: Missing argument parameter #1 in call.   
}

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

And getting the following warning in the completion function:

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中,对元组的处理比以往更加严格.

In Swift 4, tuples are treated more stricter than ever.

此关闭类型:(Void)->Void表示其中的关闭

This closure type: (Void)->Void means a closure which

  • 采用一个参数,类型为Void
  • 返回Void,表示不返回任何值
  • takes a single argument, of which the type is Void
  • returns Void, meaning returns no value

因此,请尝试以下任何一种方法:

So, try any of the followings:

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

Pass a value of type Void to the closure. (An empty tuple () is the only instance of Void.)

completion?(())

否则:

更改参数completion的类型.

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


请记住,即使在Swift 3中,两种类型的(Void)->Void()->Void也不同.因此,如果您打算表示不带参数的 closure类型,则后者是合适的.


Remember, two types (Void)->Void and ()->Void are different even in Swift 3. So the latter would be appropriate, if you intend to represent closure type with no arguments.

此更改是 SE-0029从功能应用程序中删除隐式元组splat行为,据说该功能已在Swift 3中实现,但似乎Swift 3尚未完全实现.

This change is part of SE-0029 Remove implicit tuple splat behavior from function applications which is said to be implemented in Swift 3, but it seems Swift 3 has not implemented it completely.

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

Here, I show you a simplified checking code which you can check the difference on the 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?()
        }
    }

}

这篇关于参数传递时Swift 4中的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆