Swift Equality

To check if two values are equal in Swift, we can use equality operator.

Equality Operator == takes two values as operands, one on the left and one on the right, and returns boolean value.

The return value is true if the two operands are equal, else it returns false.

The syntax to check if two values a and b are equal is

</>
Copy
a == b

Examples

In the following program, we will use Equality Operator and check if two strings are equal.

main.swift

</>
Copy
var a = "Hello World"
var b = "Hello World"
var result = a == b
print("Are the two values equal? \(result)")

Output

Swift Equality Operator Example - 1

Now, let us check if two numbers are equal using Equality Operator.

main.swift

</>
Copy
var a = 25
var b = 25
var result = a == b
print("Are the two values equal? \(result)")

Output

Swift Equality Operator Example - 2

Since the Equality Operator returns boolean value, we can use this expression as condition in if statement.

main.swift

</>
Copy
var a = 25
var b = 25
if a == b {
    print("The two values are equal.")
} else {
    print("The two values are not equal.")
}

Output

Swift Equality Operator in If Statement

Conclusion

In this Swift Tutorial, we learned how to perform Equality operation in Swift programming.