How to Check if a UITextField is Empty in Swift

When developing an iOS app, there are times when you may want to check whether a UITextField is empty.

There are several ways to determine whether a UITextField is empty.

Here, I will introduce one method in Swift to check if a TextField is empty.


Check if a TextField is empty

Let's assume you have defined a UITextField outlet named textField.

If you want to check whether this textField is empty, you can do it like this:

if textField.text?.isEmpty ?? true {
     print("The textField is empty.") 
} else { 
    print("The textField is not empty.") 
}

The ? operator after textField.text is Swift's Optional Chaining.

When you attach ? to an optional constant or variable and then call a property or method, if the value is nil, the subsequent property or method will not be executed.

In this case, if textField.text is not nil, the value of the isEmpty property is returned: true if it's empty, and false otherwise.


The ?? operator is used after an optional value, and it allows you to specify a default value when the optional is nil.

Therefore, when textField.text is nil, it becomes true.


Semantically, it is the same as the following code:

if textField.text == nil || textField.text!.isEmpty { 
    print("The textField is empty.") 
} else { 
    print("The textField is not empty.") 
}

If you need to use it repeatedly, it might be convenient to define and use a function like this:

func isTextFieldEmpty(_: UITextField) -> Bool { 
    return textField.text?.isEmpty ?? true 
}
if isTextFieldEmpty(textField) {
    print("The textField is empty.") 
} else { 
    print("The textField is not empty.") 
}

That's all for how to check if a TextField is empty in Swift.