Swift:如何将“completion”包装到异步/等待中?

Isa*_*erg 7 asynchronous async-await swift swift-concurrency

我有一个基于回调的 API。

func start(_ completion: @escaping () -> Void)
Run Code Online (Sandbox Code Playgroud)

我想在该 API 之上编写一个 async/await 包装器,将实现推迟到基于原始回调的 API。

func start() async {
    let task = Task()
    start { 
        task.fulfill()
    }
    
    return await task
}
Run Code Online (Sandbox Code Playgroud)

显然,这段代码没有连接 - 它不是真实的,. 上没有fulfill方法Task

问题:有没有办法在 Swift 中使用非结构化并发来帮助我实现这一目标?

Geo*_*e_E 19

您正在寻找延续

以下是如何在您的示例中使用它:

func start() async {
    await withCheckedContinuation { continuation in
        start(continuation.resume)
    }
}
Run Code Online (Sandbox Code Playgroud)