skip to Main Content

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


  1. This is exactly like saying await directly inside viewDidLoad; you can’t do that, it’s not async and it’s not yours. You don’t own UIViewController and so you don’t own viewDidLoad.

    '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 its handler 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 declared async, you have to end it with a Task.

    Login or Signup to reply.
  2. The initialiser of UIAlertAction looks like this

    convenience init(
        title: String?,
        style: UIAlertAction.Style,
        handler: ((UIAlertAction) -> Void)? = nil
    )
    

    The 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 a Task e.g

    Task
    {
        await Library.sharedInstance.add(book: self.book, vc: self)
    }
    

    You’ll probably want to put the

    self.removeFromLibrary = !self.removeFromLibrary
    

    in the task too, or you might have a race condition.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search