【问题标题】:Contextual closure type '() -> Void' expects 0 arguments, but 1 was used in closure body error show上下文闭包类型 '() -> Void' 需要 0 个参数,但在闭包体错误显示中使用了 1
【发布时间】:2017-11-01 06:38:48
【问题描述】:
   static func animate(_ duration: TimeInterval,
                        animations: (() -> Void)!,
                        delay: TimeInterval = 0,
                        options: UIViewAnimationOptions = [],
                        withComplection completion: (() -> Void)! = {}) {

        UIView.animate(
            withDuration: duration,
            delay: delay,
            options: options,
            animations: {
                animations()
            }, completion: { finished in
                completion()
        })
    }

在我的 swift 文件中使用上面的类并创建如下函数

SPAnimation.animate(durationScalingRootView,
                        animations: {
                            rootViewController.view.transform = CGAffineTransform.identity
        },
                        delay: delayScalingRootView,
                        options: UIViewAnimationOptions.curveEaseOut,
                        withComplection: {
                            finished in
                            //rootViewController.view.layer.mask = nil
    })

得到这个错误

上下文闭包类型 '() -> Void' 需要 0 个参数,但 1 是 用于闭包体

【问题讨论】:

  • 你应该把参数和左大括号放在同一行。

标签: swift


【解决方案1】:

问题出在这里:

withComplection: {
    finished in
    //rootViewController.view.layer.mask = nil
}

如果您查看方法声明,则完成处理程序的类型为(() -> Void)!。它不需要任何论据。你上面的闭包有一个参数 - finished。结果,出现错误。

您从闭包中删除 finished 参数:

withComplection: {
    //rootViewController.view.layer.mask = nil
}

或者您编辑您的 animate 方法以接受带有一个参数的闭包:

static func animate(_ duration: TimeInterval,
                    animations: (() -> Void)!,
                    delay: TimeInterval = 0,
                    options: UIViewAnimationOptions = [],
                    withComplection completion: ((Bool) -> Void)? = nil) {

    UIView.animate(
        withDuration: duration,
        delay: delay,
        options: options,
        animations: {
            animations()
        }, completion: { finished in
            completion?(finished)
    })
}

【讨论】:

    【解决方案2】:

    1.) 你拼错了完成

    2.) 移除 SPAnimation 函数中的闭包参数 finished in

    这不起作用的原因是您创建的函数的闭包类型只是 void。 UIView 中包含的静态函数具有闭包类型((Bool) -> Void)?,因此您必须将参数放在那里。

    要么在 SPAnimate 中更改动画函数中的闭包类型,要么在闭包调用中删除已完成的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      相关资源
      最近更新 更多