swift 在没有 return 值的情况下调用异步函数

swift calling async function without a return value

在 swift 的新结构化并发模型中是否可以在没有虚拟布尔 return 的情况下执行以下操作?

func do() async -> Bool {
  something()
  return true
}
async let foo = do()

//do other stuff
stuff()

//now I need to know that "do" has finished
await foo

我知道我可以执行以下操作,但不会 运行 同时执行:

func do() async {
  something()
}
await do()
stuff()

//cannot run "stuff" and "do" concurrently

我觉得我在这里遗漏了一个基本的想法,因为最上面的代码块做了我需要的,但由于 Bool return.

感觉像是 hack

Swift 隐式地 returns Void 用于非返回函数,所以我想这样就可以了

func do() async {
  something()
}
async let foo: Void = do() // just explicit Void so the compiler doesn't emit a warning telling you that may not be expected

//do other stuff
stuff()

//now I need to know that "do" has finished
await foo

您描述的是一个任务。例如:

Task { await `do`() }
stuff()

这将 运行 do()stuff() 同时进行。如果您需要跟踪 do() 何时完成,您可以等待任务的值:

let task = Task { await `do`() }
stuff()
await task.value // Doesn't actually return anything, but will block

这种任务运行在当前Actor的上下文中,这通常是你想要的。如果你想要一些独立于当前 Actor 的东西,你可以使用 Task.detached() 代替。

如果您以前使用过 DispatchQueues,在许多您会写 queue.async { ... } 的地方,您现在可以写 Task { ... }。新系统更强大,但如果您愿意,它可以很好地映射到旧系统。