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

时间:2019-01-29 11:35:11

标签: ios swift completion-block

==> 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)?'

2 个答案:

答案 0 :(得分:2)

您声明了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()
    })
}

P.S .:我已纠正您输入参数名称中的错字。传递隐式展开类型的输入参数也没有多大意义。将animations设置为普通的Optional并安全地将其拆开,或者将其改成非Optional(如果它永远不应该是nil)。

答案 1 :(得分:0)

在函数声明中:

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。这就是为什么它给出错误。