简体   繁体   English

Swift - 不等待异步返回

[英]Swift - Not wait for async to return

I'd like to be able to let the function doSomething() from class B to not be async and to not block it's caller thread.我希望能够让class B中的函数doSomething()async并且不阻塞它的调用者线程。 But with the following code I get this error:但是使用以下代码,我得到了这个错误:

Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type无法将“() async -> Void”类型的函数传递给期望同步函数类型的参数

and xcode try to enforce the doSomething() function from class B to be an async并且 xcode 尝试将class B中的doSomething()函数强制为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)
        }
     }
  }
}

You can wrap the function in a Task , Task您可以将函数包装在TaskTask

func doSomething() {
      Task {
        do {
           try await a.doSomething()
        } catch {
           print(error)
        }
     }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM