Home > Software engineering >  Swift: how to wrap `completion` into an async/await?
Swift: how to wrap `completion` into an async/await?

Time:11-10

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?

CodePudding user response:

You are looking for continuations.

Here is how to use it in your example:

func start() async {
    await withCheckedContinuation { continuation in
        start(continuation.resume)
    }
}
  • Related