Swift:如何将 `completion` 包装成 async/await?
Swift: how to wrap `completion` into an async/await?
我有一个基于 API 的回调。
func start(_ completion: @escaping () -> Void)
我想在 API 之上编写一个 async/await 包装器,将实现推迟到基于 API 的原始回调。
func start() async {
let task = Task()
start {
task.fulfill()
}
return await task
}
显然,此代码无法连接 - 它不是真实的,Task
上没有方法 fulfill
。
问题:有没有办法在 Swift 中使用非结构化并发来帮助我实现这个目标?
您正在寻找 continuations.
以下是如何在您的示例中使用它:
func start() async {
await withCheckedContinuation { continuation in
start(continuation.resume)
}
}
我有一个基于 API 的回调。
func start(_ completion: @escaping () -> Void)
我想在 API 之上编写一个 async/await 包装器,将实现推迟到基于 API 的原始回调。
func start() async {
let task = Task()
start {
task.fulfill()
}
return await task
}
显然,此代码无法连接 - 它不是真实的,Task
上没有方法 fulfill
。
问题:有没有办法在 Swift 中使用非结构化并发来帮助我实现这个目标?
您正在寻找 continuations.
以下是如何在您的示例中使用它:
func start() async {
await withCheckedContinuation { continuation in
start(continuation.resume)
}
}