swifttextbox

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


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

      }  
  }

Solution

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