首页 > 解决方案 > swift 4.2 无法将类型“(_)-> Void”的值转换为预期的参数类型“(()-> 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 上的错误显示 =>

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

标签: iosswiftcompletion-block

解决方案


您声明了animate函数,使其completion参数不接受输入参数。但是,finished当您在animateWithRepetition. 只需删除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()
    })
}

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


推荐阅读