gcd的封装(swift)
by 伍雪颖
override
func viewDidLoad() {
delay(2)
{
println("2s later")
}
let task =
delay(5)
{
println("call")
}
cancel(task)
}
typealias Task = (cancel :
Bool) -> ()
func delay(time:NSTimeInterval,task:()->())
-> Task? {
func dispatch_later(block:() -> ()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(time *
Double(NSEC_PER_SEC))),
dispatch_get_main_queue(),
block)
}
var closure:
dispatch_block_t? = task
var result:
Task?
let delayedClosure:
Task = {
cancel in
if
let internalClosure = closure {
if (cancel ==
false) {
dispatch_async(dispatch_get_main_queue(),
internalClosure);
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if
let delayedClosure = result {
delayedClosure(cancel: false)
}
}
return result;
}
func cancel(task:Task?)
{
task?(cancel: true)
}
版权声明:本文为博主原创文章,未经博主允许不得转载。