0

I am trying to create a required field in Swift 2. Everytime I run this code I receive no errors, but I never receive an error message with the text field is empty. The segue is always performed. Any idea what I am doing wrong?

Thanks!

@IBOutlet weak var userName: UITextField!
@IBAction func userConfermation(sender: AnyObject) {
     if userName.text!.isEmpty {
         let alertController = UIAlertController(title: "Error",
                                                 message: "Incorrect Password", preferredStyle:UIAlertControllerStyle.Alert)
         alertController.addAction(UIAlertAction(title: "Dismiss",
             style: UIAlertActionStyle.Default,handler: nil))

         self.presentViewController(alertController, animated: true, completion: nil)

     } else {
         performSegueWithIdentifier("final", sender: self)
     }
     return
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

3 Answers3

0

Hi you can check the empty string by checking userName.text character count or userName.text == "" whenever is got empty it will give you error and segue will not perfrom

Optimus
  • 800
  • 5
  • 16
0

In Swift 2 you can use a guard statement and where !text.isEmpty to check if the text field has text in it or not.

guard let text = textfield.text where !text.isEmpty else {
    // do something if it's empty
    return
}
print(text) // do something if it's not empty
owlswipe
  • 19,159
  • 9
  • 37
  • 82
0

A good way to do that would be, To create an extension of String and check for isEmpty after trimming whitespace characters :

extension String {

   var isBlank: Bool {
       return trimmingCharacters(in: .whitespaces).isEmpty
   }
}

After that you can check a string like this:

if userName.text!.isBlank {
     //do stuff
}
Agent Smith
  • 2,873
  • 17
  • 32