Created
July 14, 2015 03:08
-
-
Save barbietunnie/03984445169cd25ba3d1 to your computer and use it in GitHub Desktop.
This file contains 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
typealias dispatch_cancelable_closure = (cancel : Bool) -> Void | |
/** | |
* Delay the execution of the block by time seconds | |
* | |
* With help from Waam at http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861 | |
*/ | |
func delay(time:NSTimeInterval, closure:()->Void) -> dispatch_cancelable_closure? { | |
func dispatch_later(clsr:()->Void) { | |
dispatch_after( | |
dispatch_time( | |
DISPATCH_TIME_NOW, | |
Int64(time * Double(NSEC_PER_SEC)) | |
), | |
dispatch_get_main_queue(), clsr) | |
} | |
var closure:dispatch_block_t? = closure | |
var cancelableClosure:dispatch_cancelable_closure? | |
let delayedClosure:dispatch_cancelable_closure = { cancel in | |
if closure != nil { | |
if (cancel == false) { | |
dispatch_async(dispatch_get_main_queue(), closure!); | |
} | |
} | |
closure = nil | |
cancelableClosure = nil | |
} | |
cancelableClosure = delayedClosure | |
dispatch_later { | |
if let delayedClosure = cancelableClosure { | |
delayedClosure(cancel: false) | |
} | |
} | |
return cancelableClosure; | |
} | |
func cancel_delay(closure:dispatch_cancelable_closure?) { | |
if closure != nil { | |
closure!(cancel: true) | |
} | |
} | |
// Usage | |
let retVal = delay(2.0) { | |
println("Later") | |
} | |
delay(1.0) { | |
cancel_delay(retVal) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment