Last active
January 6, 2016 18:46
-
-
Save Danappelxx/db909736e651667111ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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