This tutorial will show you how to check if two strings are equal or not using the Swift elementsEqual()
method.
The Swift elementsEqual()
method returns a boolean value. It returns true if the two string matches. Otherwise, it returns false.
Below is how we can use the method:
string1.elementsEqual(string2)
In the above syntax, the string1
and string2
are two strings that we are going to check for equality. The returned value will be either true
or false
as we already mentioned above.
Now let’s use this method to check if two strings are equal…
Below is the given program where we are checking two strings for equality:
var string1 = "Henry"
var string2 = "Henry"
if (string1.elementsEqual(string2)) {
print("Two strings are equal")
}
else {
print("Two strings are not equal")
}
Output:
Two strings are equal
In the above program, we have used the if...else
statement to check whether the two strings are equal or not. We have passed the two strings with the elementsEqual() method in the condition of the if
statement.
In our example, we can see that both of our strings string1
and string2
have the same value. So the program executes the code of the if
statement.
But if these two strings had different values, the program run the code block inside the else statement.
Note that, the elementsEqual()
method works with case sensitivity. That means if we compare the string "Henry"
to "henry"
, then it will return false
.