swift Concurrent 异步编程
使用RunLoop
模拟await/async
- 耗时操作
func consuming(_ complete: @escaping (Int) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 30) {
complete(100)
}
}
- 模拟
await/async
func imitate() -> Result<Int, Error> {
var result: Result<Int, Error> = .failure(NSError(domain: "error", code: 200))
let runLoop = RunLoop.current
let port = Port()
consuming { code in
result = .success(code)
CFRunLoopStop(runLoop.getCFRunLoop())
}
runLoop.add(port, forMode: .default)
runLoop.run(mode: .default, before: Date().addingTimeInterval(2))
return result
}