Check If String is Empty in Swift

To check if the String value is empty I am going to use isEmpty that Swift provides.

In the code example below I have two UITextFields which are called userNameTextField and userPasswordTextField. I first read the values that each UITextField contains and then check if these values are not empty.

// Read values from text fields
let userName = userNameTextField.text
let userPassword = userPasswordTextField.text
// Check if required fields are not empty
if (userName?.isEmpty)! || (userPassword?.isEmpty)!
    // Display alert message here
    print("User name \(String(describing: userName)) or password \(String(describing: userPassword)) is empty")

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.