Why does my UITextfField seems to be NOT nil, even if I leave the field empty? My “else” part of the if-statment is not being read

感情迁移 提交于 2021-02-05 08:28:11

问题


I am practicing swift programing by making an app that holds customers' data. The app has several text fields where people are supposed to type their name, email address, phone number, and quantity of products purchased. Then with a 'submit' button they save that information into the data base. However, if one of the fields is empty, an error should be thrown and a message should appear to the user letting him/her know that one of the fields empty.

The problem is that even if the textfield is empty, the compiler is not reading it as nil, so my condition is not working.

For simplicity, I am omitting a lot of code. I will only work with one UITextField (customer's name), and my condition will check if the TextField is empty or not. If empty, it should print "Please enter a valid name." if it is NOT nil, it should print the customer's name.

class RaffleViewControler: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var customerNameTextField: UITextField!

    @IBAction func addCustomerName(_ sender: UITextField) {


    }


    @IBOutlet weak var submitButton: UIButton!


    @IBAction func submitCustomer(_ sender: UIButton) {

           if let name = customerNameTextField.text {
            print(name)

        } else {
            print("Please enter a valid name")
        }
}

Alternatively, I was also checking my condition in the following format:

@IBAction func submitCustomer(_ sender: UIButton) {

               if customerNameTextField.text != nil {
                print("Congrats. Your data is in our database")

            } else {
                print("Please enter a valid name")
            }
  }

The problem:

Even if I leave the textfield empty, the compiler does not read the "else" part of the condition. Which seems to indicate that the field is never nil. What could be happening?


回答1:


According to the Apple docs:

This string is @"" by default.

I.e. it is not nil by default.




回答2:


To check empty UITextField your can use simply

txtFieldName.text?.isEmpty

this will give you BOOL value.




回答3:


You can simply check:

if self.customerNameTextField.text == "" {
// An empty text field.
} else {
// Not empty.
}


来源:https://stackoverflow.com/questions/47215571/why-does-my-uitextffield-seems-to-be-not-nil-even-if-i-leave-the-field-empty-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!