Swift – Check if Strings are Equal

To check if two strings are equal in Swift, use equal to operator == with the two strings as operands. The equal to operator returns true if both the strings are equal or false if the strings are not equal.

We shall look into some of the Swift example programs that demonstrate how to check if two strings are equal or not.

The syntax to provide strings as operands to equal to operator is

str1 == str2

Example 1

In the following example, we have two strings str1 and str2 with the same value. We shall programmatically check if the two strings are equal using equal to operator.

main.swift

var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial in TutorialKart"

// compare if the strings are equal
if str1 == str2 {
    print("str1 and str2 are equal")
} else {
    print("str1 and str2 are not equal")
}

Output

$swift strings_equal.swift
str1 and str2 are equal
ADVERTISEMENT

Example 2

In the following example, we have two strings str1 and str2 with different values. We shall programmatically check if the two strings are not equal using equal to operator.

main.swift

var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial"

// compare if the strings are equal
if str1 == str2 {
    print("str1 and str2 are equal")
} else {
    print("str1 and str2 are not equal")
}

Output

$swift strings_equal.swift
str1 and str2 are not equal

Example 3

In the following example, we shall print the return value of the equal to operator with strings as operands.

main.swift

var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial"
var str3 = "Swift Tutorial"

print("str1 == str2 : \(str1==str2)")
print("str2 == str3 : \(str2==str3)")

Output

$swift strings_equal.swift
str1==str2 : false
str2==str3 : true

Conclusion

In this Swift Tutorial, we have learned to check if two strings are equal with the help of Swift program examples.