Checking if textfields are empty Swift

北城余情 提交于 2019-11-28 07:53:44
OOPer

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;
    }

The text property is an optional. So it can contains a String or nil.

If you want to treat nil as an empty String then just write

let isEmpty = (textField.text ?? "").isEmpty

Alternatively you can also use:

if (textField.text.characters.count > 0) {
   print("text field not empty")
} else {
   print("text field empty")
}

Give you an example picture and cover code.

@IBAction func save(_ sender: Any) {
    print("Saving...")
    //CHECK MANDATORY FIELDS
    checkMandatoryFields()
}

private func checkMandatoryFields(){

    //CHECK EMPTY FIELDS
    if let type = typeOutle.text, let name = nameOutlet.text, let address = addressOutlet.text, type.isEmpty || name.isEmpty || address.isEmpty {
        print("Mandatory fields are: ")
        errorDisplay(error: "Mandatory fields are: Type, Name, Address.")
        return
    }

    //CHECK SPACE ONLY FIELDS
}

Here's the correct answer for this.

textField.text = ""
if (textField.text.isEmpty) {
    print("Ooops, it's empty")
}

It was this check that helped me since it was necessary for me to send a request to the API, and it was necessary to send nill instead of "" if the textField is without text.

textField.text!.count > 0  ? textField.text : nil

Alternatively, you can check this way (but this option did not fit me):

if textField.text != nil {

} else {

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