Skip to content

Instantly share code, notes, and snippets.

@Danappelxx
Last active January 6, 2016 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danappelxx/db909736e651667111ad to your computer and use it in GitHub Desktop.
Save Danappelxx/db909736e651667111ad to your computer and use it in GitHub Desktop.
// Add <https://github.com/samhann/Every.swift/blob/master/NSDateComponentsExtensions.swift> here
import Foundation
import XCPlayground
struct Every {
class Executor: NSObject {
let closure: NSTimer -> Void
var timer: NSTimer!
init(closure: NSTimer -> Void) { self.closure = closure }
func execute() { closure(timer) }
deinit { print("done") }
}
init(_ duration: NSDateComponents, closure: NSTimer -> Void) {
let executor = Executor(closure: closure)
let timer = NSTimer.scheduledTimerWithTimeInterval(duration.durationInSeconds(), target: executor, selector: "execute", userInfo: nil, repeats: true)
executor.timer = timer
}
}
func main() {
var counter = 0
Every(1.seconds) { timer in
counter += 1
guard counter <= 5 else { timer.invalidate(); return }
print("ran: \(counter)")
}
}
main()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
// prints:
//ran: 1
//ran: 2
//ran: 3
//ran: 4
//ran: 5
//done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment