swift 4.2 无法将类型“(_) -> Void”的值转换为预期的参数类型“(() -> Void)?”

swift 4.2 Cannot convert value of type '(_) -> Void' to expected argument type '(() -> Void)?'

==> swift 3 版本完美运行,但 swift 4 和 swift 4.2 正在运行。

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()
    })
}

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

    var optionsWithRepeatition = options
    optionsWithRepeatition.insert([.autoreverse, .repeat])

    self.animate(
        duration,
        animations: {
            animations()
        },
        delay:  delay,
        options: optionsWithRepeatition,
        withComplection: { finished in
            completion()
    })
}

xcode 上显示错误 =>

Cannot convert value of type '(_) -> Void' to expected argument type '(() -> Void)?'

在您的函数声明中:

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

您已将完成处理程序定义为 (() -> Void)!,即它没有任何参数。

但是当你调用这个函数时:

self.animate(
        duration,
        animations: {
            animations()
        },
        delay:  delay,
        options: optionsWithRepeatition,
        withComplection: { finished in
            completion()
    })

您在完成块中提供参数 finished。这就是它给出错误的原因。

您声明了 animate 函数,使其 completion 参数没有输入参数。但是,当您在 animateWithRepetition 中调用该函数时,您正试图在闭包中调用输入参数 finished。只需删除 finished,您的代码就可以正常编译。

static func animateWithRepetition(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIView.AnimationOptions = [], withComplection completion: (() -> Void)! = {}) {

    var optionsWithRepetition = options
    optionsWithRepeatition.insert([.autoreverse, .repeat])

    self.animate(duration, animations: {
        animations()
    }, delay: delay, options: optionsWithRepeatition, withCompletion: {
        completion()
    })
}

P.S.: 我已经更正了您输入参数名称中的拼写错误。传入隐式解包类型的输入参数也没有多大意义。要么使 animations 成为正常的 Optional 并安全地展开它,要么使它成为非 Optional 如果它永远不应该 nil.