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
}
}
if let ... where ... {
Swift 3:
Swift 2:
guard ... where ... else {
You can also use the keyword
guard
:Swift 3:
Swift 2:
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.As now in swift 3 / xcode 8 text property is optional you can do it like this:
or:
Alternatively you could make an extenstion such as below and use it instead:
A compact little gem for Swift 2 / Xcode 7
Swift 4/xcode 9
Maybe i'm a little too late, but can't we check like this:
Simply comparing the textfield object to the empty string
""
is not the right way to go about this. You have to compare the textfield'stext
property, as it is a compatible type and holds the information you are looking for.Swift 2.0:
Guard:
if:
Swift 3.0:
Guard:
if: