func async<T, N>(_ delta: Double, param: T, task: @escaping (_ value: T) -> N, callFunc: @escaping (_ result: N) -> ()) { func doTaskThenCallback() { let t = task(param) DispatchQueue.main.async(execute: { callFunc(t) }) } if delta > 0.0 { DispatchQueue.global().asyncAfter( deadline: DispatchTime.now() + Double(Int64(delta * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { doTaskThenCallback() } } else { DispatchQueue.global().async { doTaskThenCallback() } } }
简单的使用小例子:
func asyncFetchImageBin(completion: ((Data?) -> Void)?) { if let bin = imageBin { completion?(bin) } else { // get bin data from cache file async(0.0, param: cacheFilePath, task: { (path) -> Data? in guard let bin = try? Data.read(from: path) else { return nil } return bin }, callFunc: { (bin) in completion?(bin) }) } }