@IBAction func addName(_ sender: AnyObject) {
let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) {
[unowned self] action in
guard let textField = alert.textFields?.first,
let nameToSave = textField.text else {
return
}
self.names.append(nameToSave)
self.tableView.reloadData()
}
I can understand most parts of the code, except the following lines:
[unowned self] action in
guard let textField = alert.textFields?.first,
I would write the code in the following way:
@IBAction func addName(_ sender: AnyObject) {
let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) {
let nameToSave = textField.text
self.names.append(nameToSave)
self.tableView.reloadData()
}
What's wrong with my code?
What's the use of [unowned self] action in
and the following guard let
code in that case?
What dose alert.textFields?.first
mean ?