62

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

      }  
  }
0

16 Answers 16

182

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  
}
4
  • 2
    what is there are two spaces in the textfield?
    – user4790024
    Commented Jan 28, 2016 at 9:32
  • 17
    Spaces in textfield: if let text = descriptionLabel.text, !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {
    – Shades
    Commented Jan 24, 2017 at 15:37
  • 4
    Coming from a Java and learning swift , "guard" seems atrocious
    – chrisl08
    Commented May 12, 2017 at 15:34
  • 2
    @chrisl08 why? It's great in some cases (e.g. in validation chains, take a look at the first example in this page : thatthinginswift.com/guard-statement-swift ) Commented May 17, 2017 at 8:58
51

Better and more beautiful use

 @IBAction func Button(sender: AnyObject) {
    if textField1.text.isEmpty || textField2.text.isEmpty {

    }
}
3
  • Doesn't work anymore in Swift 2 since the text property is optional. Check my answer below. Commented Jan 30, 2016 at 9:50
  • 1
    text property is optional. Add ! after it: if textField1.text!.isEmpty || textField2.text!.isEmpty...
    – Kaz Miller
    Commented Mar 3, 2016 at 17:06
  • Keep in mind the user may enter a space if the field is required and you should check for this condition if it matters to you.
    – xdeleon
    Commented Jun 22, 2017 at 4:50
12

another way to check in realtime textField source :

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }

 func yourNameFunction(sender: UITextField) {

    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }
0
6

if let ... where ... {

Swift 3:

if let _text = theTextField.text, _text.isEmpty {
    // _text is not empty here
}

Swift 2:

if let theText = theTextField.text where !theTextField.text!.isEmpty {
    // theText is not empty here
}

guard ... where ... else {

You can also use the keyword guard :

Swift 3:

guard let theText = theTextField.text where theText.isEmpty else {
    // theText is empty
    return // or throw
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Swift 2:

guard let theText = theTextField.text where !theTextField.text!.isEmpty else {
    // the text is empty
    return
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

This is particularly great for validation chains, in forms for instance. You can write a guard let for each validation and return or throw an exception if there's a critical error.

0
6

As now in swift 3 / xcode 8 text property is optional you can do it like this:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

or:

if (textField.text?.isEmpty ?? true) {
    // is empty
}

Alternatively you could make an extenstion such as below and use it instead:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}
5
  • 3
    This seems to be a divergent pathway for Apple to take given the idea that Swift was supposed to simplify things. Seriously. ;)
    – drew..
    Commented Jun 30, 2017 at 5:10
  • text?.isEmpty ?? true is wrong. it only unwraps the text property but the result (true) will never be called. The correct syntax is text?.isEmpty ?? false or text?.isEmpty == true. I prefer the later but in this special case that text will never return nil you can just force unwrap it return text!.isEmpty
    – Leo Dabus
    Commented Sep 2, 2018 at 19:12
  • 2
    I would say both text?.isEmpty ?? false and text?.isEmpty == true are incorrect because in both cases you assume that text cannot be nil which is wrong assumption (see Apple's definition in UITextField: open var text: String? // default is nil) so Apple here actually states that this can be nil. In practice currently it is not a nil but this might change in future especially if Apple put such comment in their code. Therefore if text is nil you should treat that as textfield is empty. Using hasText property is fine but it is available only for iOS 10.0+ Commented Sep 2, 2018 at 20:32
  • text?.isEmpty == false is the correct checking if you want to treat nil object or its String property with "" value as empty state. if object?.x.isEmpty == false { print("Is Not Empty") } else { print("Is Empty") } Commented Dec 31, 2023 at 17:09
5

use this extension

extension String {
    func isBlankOrEmpty() -> Bool {

      // Check empty string
      if self.isEmpty {
          return true
      }
      // Trim and check empty string
      return (self.trimmingCharacters(in: .whitespaces) == "")
   }
}

like so

// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.isEnabled = !text.isBlankOrEmpty()
1
  • why not simply return trimmingCharacters(in: .whitespaces).isEmpty
    – Leo Dabus
    Commented Aug 18, 2020 at 17:47
4

A compact little gem for Swift 2 / Xcode 7

@IBAction func SubmitAgeButton(sender: AnyObject) {

    let newAge = String(inputField.text!)        

if ((textField.text?.isEmpty) != false) {
        label.text = "Enter a number!"
    }
    else {
        label.text = "Oh, you're \(newAge)"

        return
    }

    }
3

Maybe i'm a little too late, but can't we check like this:

   @IBAction func Button(sender: AnyObject) {
       if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {

       }
    }
2

Okay, this might be late, but in Xcode 8 I have a solution:

if(textbox.stringValue.isEmpty) {
    // some code
} else {
    //some code
}
1
  • You can also try textField.text.isEmpty
    – Pugin
    Commented Oct 10, 2016 at 19:03
2

I used UIKeyInput's built in feature hasText: docs

For Swift 2.3 I had to use it as a method instead of a property (as it is referenced in the docs):

if textField1.hasText() && textField2.hasText() {
    // both textfields have some text
}
2
  • 1
    This has been changed to an instance property in Swift 3 .hasText
    – Leo Dabus
    Commented Apr 19, 2017 at 17:14
  • 1
    Problem is a user could add simple spaces too
    – user1094081
    Commented Oct 4, 2017 at 7:56
2

Swift 4.x Solution


@IBOutlet var yourTextField: UITextField!

 override func viewDidLoad() {
     ....
     yourTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
  }

 @objc func actionTextFieldIsEditingChanged(sender: UITextField) {
     if sender.text.isEmpty {
       // textfield is empty
     } else {
       // text field is not empty
     }
  }
2
  • 3
    How does that answer the question? Commented Apr 12, 2018 at 8:33
  • @rollstuhlfahrer, thanks! When I first gave the answer, I have had given the answer for the latest Swift version. Thanks for pointing out. Hope this answer helps.
    – Hemang
    Commented Apr 12, 2018 at 11:26
2

Swift 4.2

You can use a general function for your every textField just add the following function in your base controller

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false

    }else{
        return true
    }
}
1
  • 2
    Single line code: return (text.trimmingCharacters(in: .whitespaces).isEmpty) ? false : true Commented Jun 11, 2019 at 6:17
0

I just tried to show you the solution in a simple code

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}
0

It's too late and its working fine in Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }
0

Swift 4/xcode 9

IBAction func button(_ sender: UIButton) {
        if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
                ..............
        }
}
-1

Easy way to Check

if TextField.stringValue.isEmpty {

}
1
  • Note, we've received reports of this not working in XCode 8.
    – TylerH
    Commented Jun 14, 2016 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.