Search code examples
iosswifttimernstimerswift3

Cannot convert (Timer!) -> Void to ((CFRunLoopTimer?) ->Void)! - Converting NSTimer extension to Swift 3


I am trying to convert a Pod I am using in my project to Swift 3. I didn't write it, but the original author has not updated it so I forked it any I'm trying to do it myself. But...

I get this error trying to convert an extension to NSTimer to Swift 3: Cannot convert value of type '(Timer!) -> Void' to expected argument type '((CFRunLoopTimer?) -> Void)!

It seems that the Swift 3 handler type, (Timer!) -> Void is not compatible with the old school CFRunLoop style handlers, but I am not sure how to convert this over while maintaining compatibility with iOS 9.

I am pasting the code below, as converted by Xcode. You can find the original code at https://github.com/entotsu/TKSubmitTransition/blob/master/SubmitTransition/Classes/NSTimerEx.swift

Cheers

import Foundation
extension Timer {
    class func schedule(delay delay: TimeInterval, handler: (Timer!) -> Void) -> NSTimer {
        let fireDate = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler) // Error on this line
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }

    class func schedule(repeatInterval interval: TimeInterval, handler: @escaping (Timer!) -> Void) -> Timer {
        let fireDate = interval + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler) // And this line
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
}

Solution

  • Try like this:

    extension Timer {
        class func schedule(delay: TimeInterval, handler: ((Timer?) -> Void)!) -> Timer! {
            let fireDate = delay + CFAbsoluteTimeGetCurrent()
            let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
            CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes)
            return timer
        }
        class func schedule(repeatInterval interval: TimeInterval, handler: ((Timer?) -> Void)!) -> Timer! {
            let fireDate = interval + CFAbsoluteTimeGetCurrent()
            let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
            CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes)
            return timer
        }
    }