Reputation: 121
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;
}
Upvotes: 4
Views: 37616
Reputation: 847
Alternatively you can also use:
Swift 3:
if (textField.text.characters.count > 0) {
print("text field not empty")
} else {
print("text field empty")
}
Swift 4.x and above:
if (textField.text.count > 0) {
print("text field not empty")
} else {
print("text field empty")
}
Upvotes: 3
Reputation: 2477
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
}
Upvotes: 1
Reputation: 595
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 {
}
Upvotes: 0
Reputation:
Here's the correct answer for this.
textField.text = ""
if (textField.text.isEmpty) {
print("Ooops, it's empty")
}
Upvotes: 0
Reputation: 47906
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;
}
Upvotes: 37
Reputation: 59536
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
Upvotes: 5