swift - "Extra argument ' 当传递 Swift 闭包时完成 ' in call"

标签 swift

我扩展了 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/

相关文章:

ios - 我可以知道这个最好的 UI/UX 方法是什么吗?

ios - 相同位置 2 个按钮在 swift 中?

swift - 无法从 Swift 中的子类调用主 ViewController 中的函数

ios - Swift NSArray 突变

ios - 让 UITextView 的键盘消失,同时保持返回功能

swift - 将数字签名添加到 PDF Swift

swift - 如何编写在对象生命周期后期计算的 swift 属性

ios - 在 XIB 中使用多个 UITableView

SwiftUI:通过外部调用的函数更改@State 变量?

ios - 无法从黑色更改 UIView 背景颜色