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) }
本文介绍了一种在Swift中实现延迟任务的方法,并提供了一个取消该任务的功能。通过使用GCD(Grand Central Dispatch),可以实现在指定时间后执行某个闭包,并且允许在任务执行前取消它。

1万+

被折叠的 条评论
为什么被折叠?



