Compare Two Strings in Swift

The two Swift code snippets below are examples of how to compare if two Strings are equal.

Check if Two Strings are Equal Using elementsEqual()

Let’s assume the two Strings are constants and we need to compare them:

let password = "HelloWorld"
let repeatPassword = "HelloWorld"
if ((password.elementsEqual(repeatPassword)) == true)
   print("Passwords are equal")
} else {
   print("Passwords are not equal")

Compare the Text in Two UITextFields

The below code snippet compares if the two Strings that are read from different UITextFields are equal. Let’s assume we have two UITextFields:

  • userPasswordTextField
  • and repeatPasswordTextField
// Compare if provided passwords are equal
if ((userPasswordTextField.text?.elementsEqual(repeatPasswordTextField.text!))! != true)
   // Passwords do not match. Display alert message and return

Compare two Strings using caseInsensitiveCompare()

The code snippet below performs case insensitive comparison of two Strings in Swift:

let valueExpected = "SUCCESS"
let valueProvided = "success"
if valueExpected.caseInsensitiveCompare(valueProvided) == ComparisonResult.orderedSame
    print("Strings are equal")

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.