Search code examples
iosswiftasync-awaitstructured-concurrency

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. 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)
        }
     }
  }
}

Solution

  • You can wrap the function in a Task, Task

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