I do apologize in advance for asking such a silly question, yet I didn't quite get what I wanted to know from the other answers out there. Here is the sample code of custom delegate protocol from the Ray Wenderlich iOS course
protocol AddItemViewControllerDelegate: class {
func addItemViewControllerDidCancel(_ controller: AddItemViewController)
func addItemViewController(_ controller: AddItemViewController,
didFinishAdding item: ChecklistItem) }
Though the definition of protocol is quite clear, it is kind of contract that should be conformed in order to be used. But here is the implementation of the function of the protocol in the body of the conforming class
func addItemViewController(_ controller: AddItemViewController,
didFinishAdding item: ChecklistItem) {
let newRowIndex = items.count
items.append(item)
let indexPath = IndexPath(row: newRowIndex, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
dismiss(animated: true, completion: nil)
}
And there is no actual usage of controller argument, and what is didFinishAdding? As far as I understand, didFinishAdding is just an external name for the internal argument item. But how it works, how it could be understand from the body of the protocol that controller named AddItemViewController sends ChecklistItem to the conforming delegate, or is it some pre-defined function type?
Here we talk about Swift code style convention.
The didFinishAdding
is an argument description, which makes it more clear for the caller to understand, what it should be. Of course, you see that the type of the second argument is ChecklistItem
, but in order for developer not to be confused, you make this short explanation, which item exactly should be passed to the function.
In your example controller
argument is not used, I guess, because there is no need for it in this particular implementation. However, that is the general style of delegates: you say who did the action and what is the subject of it. There is might be a case when you will need to know what AddItemViewController
added an item.