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

跟風遠走 提交于 2019-12-11 02:26:31

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/39595873/cannot-convert-timer-void-to-cfrunlooptimer-void-converting-nsti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!