Swift - 不等待异步返回

bar*_*mes 7 ios async-await swift structured-concurrency

我希望能够让该函数doSomething()class B存在async并且不阻止它的调用者线程。但使用以下代码我收到此错误:

无法将“() async -> Void”类型的函数传递给需要同步函数类型的参数

并且 xcode 尝试强制该doSomething()函数class B成为async

class A {
    func doSomething() async throws {
       //perform 
    }
}

class B {
   let a = A()
   func doSomething() {
      DispatchQueue.global().async {
        do {
           await try a.doSomething()
        } catch {
           print(error)
        }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

cor*_*ora 21

您可以将函数包装在Task中,Task

func doSomething() {
      Task {
        do {
           try await a.doSomething()
        } catch {
           print(error)
        }
     }
  }
Run Code Online (Sandbox Code Playgroud)

  • 使用 Xcode 13.2,可以使用 iOS13+ 中的所有新并发 API。https://developer.apple.com/documentation/xcode-release-notes/xcode-13_2-release-notes (2认同)