So, I've finished the consolidation challange of day 32, things are finally starting to make logical sense to me.
I've finished it with some help of previously written code, and I would like some help/clarification about this specific code.
@objc func addItemAlert() {
//Setup of alert controller
let alertController = UIAlertController(title: "Add item", message: "Add the item that you would prefer to add", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
alertController.addTextField()
//Is this a closure?
let submitAction = UIAlertAction(title: "Submit", style: .default) {
[weak self, weak alertController] action in
guard let answer = alertController?.textFields?[0].text else { return }
self?.submit(answer.lowercased())
}
alertController.addAction(submitAction)
//Presenting controller
present(alertController, animated: true)
}
func submit(_ answer: String) {
let indexPath = IndexPath(row: 0, section: 0)
shoppingList.insert(answer, at: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
Specifically these two blocks of code:
//Is this a closure?
let submitAction = UIAlertAction(title: "Submit", style: .default) {
[weak self, weak alertController] action in
guard let answer = alertController?.textFields?[0].text else { return }
self?.submit(answer.lowercased())
}
alertController.addAction(submitAction)
//Presenting controller
present(alertController, animated: true)
}
func submit(_ answer: String) {
let indexPath = IndexPath(row: 0, section: 0)
shoppingList.insert(answer, at: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
How does 'sumbmitAction' work? does it run when submit is being called, or is it the other way around? Some clarification on this code would be appreciated thanks alot.