我扩展了 UIView 上的动画功能,添加了一些用于缩放的快捷功能,如下所示。
extension UIView {
class func animatePressed(viewToAnimate: UIView, complete: ((Bool) -> Void)) {
UIView.animateWithDuration(0.20, delay: 0, options: UIViewAnimationOptions.allZeros, animations: {
viewToAnimate.transform = CGAffineTransformScale(viewToAnimate.transform, scale, scale)
}, completion: complete)
}
}
当我尝试调用此函数时会出现此问题。由于我只关心动画何时完成,因此我使用“_”符号作为参数占位符。
UIView.animatePressed(messagesImage, complete: { _ in
self.delegate.newSubViewControllerRequested(UIStoryboard.messageListViewController()!)
})
我收到以下编译器错误...
Extra argument 'complete' in call
如果我将代码更改为以下任一内容,编译器将停止提示。
UIView.animatePressed(messagesImage, complete: { _ in
if 1 == 1 {
self.delegate.newSubViewControllerRequested(UIStoryboard.messageListViewController()!)
}
})
UIView.animatePressed(messagesImage, complete: { _ in
self.delegate.newSubViewControllerRequested(UIStoryboard.messageListViewController()!)
return
})
这是 Swift 中的一个错误还是我在这里完全遗漏了一些东西?
最佳答案
都不是。这不是 Swift 错误,并且您没有遗漏任何内容 - 因为事实上您已经正确解决了问题!
问题是,作为一种快捷方式,如果匿名函数仅包含一行,Swift 会尝试将其用作返回值。但是,该返回值对于 (Bool) -> Void
无效。
换句话说,当你这样说时:
UIView.animatePressed(messagesImage, complete: { _ in
self.delegate.newSubViewControllerRequested(UIStoryboard.messageListViewController()!)
})
这正如你所说的:
UIView.animatePressed(messagesImage, complete: { _ in
return self.delegate.newSubViewControllerRequested(UIStoryboard.messageListViewController()!)
})
但你不能这么说,因为你的 newSubViewControllerRequested
返回一个实际的非 Void 值。所以现在你遇到了类型不匹配;此匿名函数不符合所需的签名。
因此,解决方法就是您所做的 - 向匿名函数添加更多行(以抑制快捷方式),和/或提供显式的 void 返回值。
关于swift - "Extra argument ' 当传递 Swift 闭包时完成 ' in call",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303094/