Swift - Not wait for async to return

13.1k Views Asked by At

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. But with the following code I get this error:

Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type

and xcode try to enforce the doSomething() function from class B to be an 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)
        }
     }
  }
}
1

There are 1 best solutions below

5
On BEST ANSWER

You can wrap the function in a Task, Task

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