Swift String elementsEqual()

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) returns true.
  • str1 and str3 are not equal. Hence, str1.elementsEqual(str3) and str3.elementsEqual(str1) return false.

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?