无法转换(计时器!) - >无效((CFRunLoopTimer?) - > Void)! - 将NSTimer扩展转换为Swift 3

时间:2016-09-20 13:46:49

标签: ios swift timer nstimer swift3

我正在尝试将我在项目中使用的Pod转换为Swift 3.我没有写它,但是原作者没有更新它所以我把它分叉,我自己试图做。但...

尝试将扩展程序转换为NSTimer到Swift 3时出现此错误: Cannot convert value of type '(Timer!) -> Void' to expected argument type '((CFRunLoopTimer?) -> Void)!

似乎Swift 3处理程序类型(Timer!) -> Void与旧学校CFRunLoop样式处理程序不兼容,但我不确定如何在保持与iOS 9的兼容性的同时将其转换。< / p>

我正在粘贴下面的代码,由Xcode转换。您可以在https://github.com/entotsu/TKSubmitTransition/blob/master/SubmitTransition/Classes/NSTimerEx.swift

找到原始代码

干杯

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 个答案:

答案 0 :(得分:13)

试试这样:

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