01.Swift|01.Swift - Timer - block

iOS10以后Timer新增了Timer.init()系列方法,这些方法都提供了block回调,非常好用,但是每次使用都要判断系统版本:
if #available(iOS 10.0, *) { Timer.init(timeInterval: 1, repeats: true) { (t:Timer) in print("1") } } else { // Fallback on earlier versions }

【01.Swift|01.Swift - Timer - block】为了适配低版本,也为了更好封装,我们最好还是用一个extension单独管理计时器
extension Timer { }

一、普通计时器,每次回调执行操作
/* interval: 计时器间隔 * repeats:是否重复 * block:每重复一次的回调 */ class func initRepeat(interval:TimeInterval, repeats:Bool, block: ()->()) -> Timer { let timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(Timer.blockRepeat(_:)), userInfo: block, repeats: repeats) return timer }@objc private class func blockRepeat(_ timer: Timer) { if let block = timer.userInfo as? ()->() { block() } }

二、计数计时器,每次回调返回当前计数次数
/* interval:计时器间隔 * repeatTimes:重复次数 * blockRepeats: 每重复一次的回调,并返回当前次数 */ class func initRepeat(interval:TimeInterval, repeatTimes:Int, blockRepeats: (_ times:Int)->()) -> Timer { ... }@objc private class func blockRepeatTimeParam(_ timer:Timer) { ... }

    推荐阅读