bibscy
bibscy

Reputation: 2708

error cannot convert value of type `Void` to expected argument type `() -> Void` UIAlertController

Very often I have to show an alert to the user and I find myself writing the same code over and over again, so I built a convenience method.

When self.convenience.showAlertToUser() is called in viewDidLoad I get error for argument doThisAction cannot convert value of type Void to expected argument type () -> Void. I don't understand why, because I pass in an argument of that type. Also, I don't know if I am creating a retain cycle, so I would appreciate your help.

class ConvenienceMethods {

   func showAlertToUser(alertMessage: String = "",actionOkTitle:String, actionCancelTitle:String, controller: UIViewController, cancelAction: Bool, doAction: @escaping (() -> Void)) {

    let customAlert = UIAlertController(title: "", message: alertMessage, preferredStyle: .alert)
    let actionCancel = UIAlertAction(title: actionCancelTitle, style: .cancel, handler: nil)
    let actionOk =  UIAlertAction(title: actionOkTitle, style: .default, handler: { (action: UIAlertAction) in
        doAction()
    })

    if cancelAction == true {
        customAlert.addAction(actionCancel)
    }
        customAlert.addAction(actionOk)
        controller.present(customAlert, animated: true, completion: nil)
  }
}


  class ManageFeedbackTableViewController {
       let convenience = ConvenienceMethods()

    override func viewDidLoad() {
        super.viewDidLoad()
      let doThisAction = self.segueWith(id: "segueID")
       self.convenience.showAlertToUser(alertMessage: "someMessage", actionOkTitle: "OK", actionCancelTitle: "No", controller: self, cancelAction: false, doAction: doThisAction)
}

    //perform an action
     func segueWith(id: String) -> Void{
     self.performSegue(withIdentifier: id, sender: self)
  }
}

Upvotes: 0

Views: 2617

Answers (2)

CZ54
CZ54

Reputation: 5588

Because you are to passing a reference to the function but the result itself.

Replace let doThisAction = self.segueWith(id: "segueID")

By :

let doThisAction = { self.segueWith(id: "segueID") }

Upvotes: 1

Rohi
Rohi

Reputation: 475

@bibscy, doThisAction is a closure to which we can assign a block of code within "{ }" as follows:- let doThisAction = { self.segueWith(id: "segueID") } which will work.

Upvotes: 1

Related Questions