I’m trying to convert my swift code to use async/await. I have the following code
alert.addAction(UIAlertAction(title: "Add to Library", style: .default) { _ in
await Library.sharedInstance.add(book: self.book, vc: self)
self.removeFromLibrary = !self.removeFromLibrary
});
When I try to compile, I get the following error Invalid conversion from ‘async’ function of type ‘(UIAlertAction) async -> Void’ to synchronous function type ‘(UIAlertAction) -> Void’
What I’m I doing wrong?
2
Answers
This is exactly like saying
await
directly insideviewDidLoad
; you can’t do that, it’s notasync
and it’s not yours. You don’t own UIViewController and so you don’t ownviewDidLoad
.'async' call in a function that does not support concurrency
This is just another form of the same thing. In the same way, here the trouble is that you don’t own UIAlertController so you don’t own
addAction
so you don’t own UIAlertAction so you don’t own the type of closure of itshandler
closure.You would have to initialize a Task at that point. The
async
chain must always end somewhere… If you can’t end it at a function that Apple has already declaredasync
, you have to end it with a Task.The initialiser of
UIAlertAction
looks like thisThe handler is an optional wrapping
(UIAlertAction) -> Void
but your closure that you pass to it has an asynchronous call in it, so its type is(UIAlertAction) async -> Void
. This means it has the wrong type and cannot be used in place of a synchronous function.You’ll need to wrap your
await
call in aTask
e.gYou’ll probably want to put the
in the task too, or you might have a race condition.