简单封装 GCD 延迟操作,可取消延迟操作

struct Delay {
typealias Task = (Bool) -> ()

@discardableResult
static func after( time: TimeInterval, task: @escaping() -> ()) -> Task? {
    func dispatch_later(block: @escaping() -> ()) {
        let t = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: t, execute: block)
    }
    var closure: (() -> ())? = task
    var result: Task?
    let delayedClosure: Task = { cancel in
        if let internalClosure = closure {
            if cancel == false {
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        closure = nil
        result = nil
    }
    result = delayedClosure
    dispatch_later {
        if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    return result
}
static func cancel( task: Task?) {
    task?(true)
}

}

你可能感兴趣的:(简单封装 GCD 延迟操作,可取消延迟操作)