Bronze Challenge question

#1

@IBAction func addButtonPressed(sender: UIButton) { guard let text = itemTextField.text else { return } todoList.addItem(text) itemTextField.text = nil tableView.reloadData() }
I’m puzzled as to why setting itemTextField.text to nil doesn’t solve both issues (I know it really doesn’t, since the text field could have been edited down to an empty String, but still, for the case of just tapping Insert multiple times… ).

Yes, the text field clears, but clicking immediately again on Insert adds an empty item to the list. Why isn’t the ‘guard’ statement preventing this? Shouldn’t itemTextField.text still be nil at that point?

Xcode 7.3 / Swift 2.2

#2

I’m puzzuled, too.
It seems the setter for UITextField.text assigns empty instead of nil when we try to set nil.
So, we have to handle both of nil and empty in the guard condition.

    @IBAction func addButtonPressed(sender: UIButton) {
        guard let text = itemTextField.text where !text.isEmpty else {
            return
        }
        todoList.addItem(text)
        itemTextField.text = nil
        print("text: \(itemTextField.text)") // you can see it's not nil.
        tableView.reloadData()
    }