Swift – Check if Strings are Equal

In this tutorial, we will learn how to check if two strings are equal in Swift programming.

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 and 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.

Example 1 – Swift program to check if two strings are equal

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

Example 2 – Swift program to check if two strings are equal

In the following example, we have two strings str1 and str2 with the 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 – Strings equal to operator return value

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.