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

Digvijaysinh Gida picture Digvijaysinh Gida · Jan 29, 2019 · Viewed 10.3k times · Source

==> swift 3 version in perfect work but swift 4 and swift 4.2 in now working.

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

Error display on xcode =>

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

Answer

Dávid Pásztor picture Dávid Pásztor · Jan 29, 2019

You declared the animate function such that its completion parameter takes no input arguments. However, you are trying to call an input argument, finished in your closure when you call that function in animateWithRepetition. Just remove finished and your code compiles fine.

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.: I've corrected the typos in your input argument names. Passing in an input argument of implicitly unwrapped type also doesn't make much sense. Either make animations a normal Optional and safely unwrap it or rather make it non-Optional if it should never be nil.