NSTimerの拡張を作ります。
NSTimer+Closure.swift
import Foundation
// (c) 2014 Nate Cook, licensed under the MIT license
extension NSTimer {
class func scheduledTimerWithTimeInterval(interval: NSTimeInterval, repeats: Bool, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let repeatInterval = repeats ? interval : 0
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, repeatInterval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
}
使い方は以下のとおり
var count = 0
NSTimer.scheduledTimerWithTimeInterval(1, repeats: true) { timer in
println(++count)
if count >= 10 {
timer.invalidate()
}
}
こちらのものを転載させて頂きました。
https://gist.github.com/natecook1000/b0285b518576b22c4dc8