Search code examples
iosswifthandler

How to efficiently use handlers in swift?


I have recently started learning Swift and the Xcode documentation. Nonetheless, I am facing quite some problems with the handlers in general as seen in the code below:

let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
    // Delete the row from the data source
    self.restaurantNames.remove(at: indexPath.row)
    self.restaurantLocations.remove(at: indexPath.row)
    self.restaurantTypes.remove(at: indexPath.row)
    self.restaurantIsVisited.remove(at: indexPath.row)
    self.restaurantImages.remove(at: indexPath.row)

    self.tableView.deleteRows(at: [indexPath], with: .fade)

    // Call completion handler with true to indicate
    completionHandler(true)
}

I don't quite understand why did the tutorial that I am following (which is appcoda) has written (action, sourceView, completionHandler). For better understanding I tried changing this tuple to (action, sourceView, completionHandler) and it yielded the same result, which surprised me a lot. Therefore I wanted to ask you, what should I put inside these tuples and what is there purpose?


Solution

  • These are the parameters for your closure that you get when the completionHandler is called. This is what they are:

    action:

    The object containing information about the selected action.

    sourceView:

    The view in which the action was displayed.

    completionHandler:

    The handler block for you to execute after you have performed the action. This block has no return value and takes the following parameter: actionPerformed A Boolean value indicating whether you performed the action. Specify true if you performed the action or false if you were unable to perform the action for some reason.

    Reference and more information here and here.