参数传递时Swift 4中的编译错误 [英] Compile error in Swift 4 on parameter passing
问题描述
我在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屋!