Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a text field is empty or not in swift

Tags:

swift

textbox

I am working on the code below to check the textField1 and textField2 text fields whether there is any input in them or not.

The IF statement is not doing anything when I press the button.

 @IBOutlet var textField1 : UITextField = UITextField()  @IBOutlet var textField2 : UITextField = UITextField()  @IBAction func Button(sender : AnyObject)    {      if textField1 == "" || textField2 == ""        {    //then do something        }     } 
like image 876
Gokhan Dilek Avatar asked Jun 08 '14 03:06

Gokhan Dilek


People also ask

How do I check if multiple text fields are empty in Swift?

In Swift 2 I would do: if firstNameField. text. character. count == 0 { ..

How do I check if a file is empty in Swift?

Swift – Check if String is Empty To check if string is empty in Swift, use the String property String. isEmpty . isEmpty property is a boolean value that is True if there are no any character in the String, or False if there is at least one character in the String.


1 Answers

Simply comparing the textfield object to the empty string "" is not the right way to go about this. You have to compare the textfield's text property, as it is a compatible type and holds the information you are looking for.

@IBAction func Button(sender: AnyObject) {     if textField1.text == "" || textField2.text == "" {         // either textfield 1 or 2's text is empty     } } 

Swift 2.0:

Guard:

guard let text = descriptionLabel.text where !text.isEmpty else {     return } text.characters.count  //do something if it's not empty 

if:

if let text = descriptionLabel.text where !text.isEmpty {     //do something if it's not empty       text.characters.count   } 

Swift 3.0:

Guard:

guard let text = descriptionLabel.text, !text.isEmpty else {     return } text.characters.count  //do something if it's not empty 

if:

if let text = descriptionLabel.text, !text.isEmpty {     //do something if it's not empty       text.characters.count   } 
like image 197
Brian Tracy Avatar answered Oct 06 '22 03:10

Brian Tracy