Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if textfields are empty Swift

I know there are tons of stack overflow pages out there that explain how to do this but everytime I take the code from here and put it in i get the same error and that error is value of "string?" has no member "text" Any ideas of a solid way that will work for checking if a textfield is empty in swift?

let userEmail = userEmailTextField.text;
// Check for empty fields
if (userEmail.text.isEmpty) {
    // Display alert message
    return;
}
like image 413
404Developer Avatar asked Nov 27 '22 22:11

404Developer


1 Answers

This post is given a good answer (it's a pity it has no "accepted" mark). Use (self.field.text?.isEmpty ?? true).

Assume your textField is declared as:

    @IBOutlet weak var textField: UITextField!

You can check its emptiness with:

    if textField.text?.isEmpty ?? true {
        print("textField is empty")
    } else {
        print("textField has some text")
    }

To use the variables in your edited post:

    let userEmail = userEmailTextField.text;
    // Check for empty fields
    if userEmail?.isEmpty ?? true {
        // Display alert message
        return;
    }

or:

    // Check for empty fields
    if userEmailTextField.text?.isEmpty ?? true {
        // Display alert message
        return;
    }
like image 162
OOPer Avatar answered Mar 26 '23 21:03

OOPer