5

I have a callback based API.

func start(_ completion: @escaping () -> Void)

I'd like to write an async/await wrapper on top of that API, deferring the implementation to original callback based API.

func start() async {
    let task = Task()
    start { 
        task.fulfill()
    }
    
    return await task
}

Obviously, this code doesn't connect - it's not real, there is no method fulfill on Task.

Question: is there a way to use unstructured concurrency in Swift so that it would help me achieve this?

George
  • 25,988
  • 10
  • 79
  • 133
Isaaс Weisberg
  • 2,296
  • 2
  • 12
  • 28
  • 3
    You are looking for [continuations](https://www.hackingwithswift.com/quick-start/concurrency/how-to-use-continuations-to-convert-completion-handlers-into-async-functions) – George Nov 09 '21 at 18:08
  • Oh... hah, that was quite not very long... I will gladly accept this as the right answer, if you put copy paste this as an answer... :) – Isaaс Weisberg Nov 09 '21 at 18:10
  • @George could you help me with [that](https://stackoverflow.com/q/75475683/2725435) question? It was marked as a similar, but I got confused. – Bartłomiej Semańczyk Feb 16 '23 at 17:43
  • 1
    @BartłomiejSemańczyk I recommend reading the HWS article linked in my answer below, and also the documentation [here](https://developer.apple.com/documentation/swift/checkedcontinuation). There are many resume methods, each one suiting individual cases. – George Feb 17 '23 at 03:13

1 Answers1

12

You are looking for continuations.

Here is how to use it in your example:

func start() async {
    await withCheckedContinuation { continuation in
        start(continuation.resume)
    }
}
George
  • 25,988
  • 10
  • 79
  • 133