Swift GCD的使用1

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 { () -> () in
        if let delayedClosure = result {
            delayedClosure(cancel: false)
        }
    }
    return result
}
//取消
func cancel(task : Task?) {
    task?(cancel: true)
}

 

posted @ 2015-03-04 10:24  云影风雨  阅读(192)  评论(0编辑  收藏  举报