简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM