Annabelle Sykes Annabelle Sykes - 7 months ago 29
Swift Question

Error: Cannot convert value of type '(_, _) -> Void' to expected argument type '((UIAlertAction) -> Void)?'

I have a button created in my

Main.storyboard
, which has a name (a
var
) named
deleteButton
. This button is in each cell.

When the user presses the button, an alert pops up to confirm the deletion. Here is the code.

@IBAction func deletePinpoint(sender: UIButton) {

let alertController = UIAlertController(title: "Delete pinpoint", message: "Do you want to delete this pinpoint?", preferredStyle: UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action, indexPath) -> Void in

if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
let pinpointToDelete = self.fetchResultController.objectAtIndexPath(sender.tag) as! Pinpoints
managedObjectContext.deleteObject(pinpointToDelete)

do {
try managedObjectContext.save()
} catch {
print(error)
}
}
}))

alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

self.presentViewController(alertController, animated: true, completion: nil)
}


In the
cellForRowAtIndexPath:
method, I have declared this line:

cell.deleteButton.tag = indexPath.row


I get the error on the 3rd line (starting with
alertController.addAction
) saying:


Cannot convert value of type '(_, _) -> Void' to expected argument type '((UIAlertAction) -> Void)?'


How do I fix this?

Answer

The handler's parameter of UIAlertAction constructor, takes the selected action object as its only parameter.

Instead of this:

alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action, indexPath) -> Void in

you will want this:

alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction) -> Void in
Comments