0
@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 ?

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Wilson
  • 49
  • 6
  • You are asking about two completely separate lines of code, not one. The two have nothing to do with each other. – rmaddy Jan 09 '17 at 03:29
  • http://stackoverflow.com/questions/24320347/shall-we-always-use-unowned-self-inside-closure-in-swift refer this answer – Himanshu Moradiya Jan 09 '17 at 04:11

1 Answers1

1

The saveAction has a closure block at the end which is basically what will happen when the save action is triggered. Inside closures, you need to reference the variables with self. When you use self it creates a strong reference with the closure. The [unowned self] basically means tells not to create a strong reference with the closure.

For the next part, the guard keyword is used to ensure that a value is not nil. Here, the alert.textFields?.first is an optional textfield. So, if you do alert.textFields!.first!.text! and the textField turns out to be nil, your app will crash. To prevent this, the guard keyword is used. If the value in it turns out to be nil, the control will enter the else block and return skipping all the below code.

Have a look at this article if you want to read more about strong and weak references.

ebby94
  • 3,131
  • 2
  • 23
  • 31