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 } }
In Swift 2 I would do: if firstNameField. text. character. count == 0 { ..
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With