Ways to compare two strings in Swift

In this tutorial, we will see how to compare two strings to determine if they are equal or not in Swift. There are so many practical applications of this task like comparing passwords and re-type passwords if they are equal then only validate a user and create a password.

We can do this in many ways described as:

  1. Using the “==” operator(Case Sensitive).
  2. Using “==” operator(Case Insensitive).
  3. Using elementsEqual method.

Method 1: Using the “==” operator(Case Sensitive)

The first method describes checking the two strings using “==” operator. This operator is known as Equal to which returns a bool value if the strings are equal. Also, it will return false if the strings are not in the same case.

This is just a two-line code that first declares string1 and then string2 compares it with the “==” operator and returns a bool value as-

let password = "[email protected]"
let retypepassword = "[email protected]"

print(password == retypepassword)

Output-

true

Method 2: Using “==” operator(Case Insenitive)

This method is similar to the above method but the difference lies in case. Sometimes, while comparing strings, we do not need to check the case. Just the alphabet and its sequence matters. So modifying the above code by changing both the strings in lowercase will accomplish this task.

So here is the snippet part-

let password = "[email protected]"
let retypepassword = "[email protected]"

print(password.lowercased() == retypepassword.lowercased())

Output-

true

Method 3: Using elementsEqual method

The above methods simply use “==” operator to check for the string equality. Also, there as a built-in method  elementsEqual that returns a bool value if the two strings are equal. Here’s the implementation:

let password = "[email protected]"
let retypepassword = "[email protected]"
if ((password.elementsEqual(retypepassword)) == true)
{
   print("true")
} else {
   print("false")
}

Output

true

So we have discussed three methods of comparing two strings in Swift which has so many practical applications. I hope you found it helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *