Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift String elementsEqual()
In this tutorial, we will learn about the Swift elementsEqual() method with the help of examples.
The elementsEqual() method returns true if two strings are equal. If not, it returns false.
Example
var str1 = "Learn Swift"
var str2 = "Learn Swift"
// comparing str1 with str2
var result = str1.elementsEqual(str2)
print(result)
// Output: true
elementsEqual() Syntax
The syntax of the string elementsEqual() method is:
string.elementsEqual(str: String)
Here, string is an object of the String class.
elementsEqual() Parameters
The Equals() method takes a single parameter:
- str - the string to be compared with the given string
elementsEqual() Return Value
The elementsEqual() method returns:
- true - if the strings are equal
- false - if the strings are not equal
Example 1: Swift String elementsEqual()
var str1 = "Learn Swift"
var str2 = "Learn Swift"
var str3 = "Learn Java"
// comparing str1 with str2
var result = str1.elementsEqual(str2)
print(result) // true
// comparing str1 with str3
result = str1.elementsEqual(str3)
print(result) // false
// comparing str3 with str1
result = str3.elementsEqual(str1)
print(result) // false
Here,
- str1 and str2 are equal. Hence,
str1.elementsEqual(str2)returnstrue. - str1 and str3 are not equal. Hence,
str1.elementsEqual(str3)andstr3.elementsEqual(str1)returnfalse.
Example 2: Check if Two Strings Are Equal
var str1 = "Learn Swift"
var str2 = "Learn Java"
// if str1 and str2 are equal, the result is true
if (str1.elementsEqual(str2)) {
print("str1 and str2 are equal")
}
else {
print("str1 and str2 are not equal")
}
Output
str1 and str2 are not equal
Example 3: elementsEqual() With Case
var str1 = "Learn Swift"
var str2 = "learn Swift"
// comparing str1 with str2
var result = str1.elementsEqual(str2)
print(result) // false
When "Learn Swift" is compared to "learn Swift", we get false. This is because elementsEqual() takes the letter case into consideration.
Did you find this article helpful?