Two instances are equal if they have the same value. Equality is used to determine the equality of two value types. For instance, two strings are equal if they have the same text value. The == operator is used to check for equality. The following example presents equality checking for two Int numbers (Int is a value type):
let firstNumber = 1
let secondNumber = 1
if firstNumber == secondNumber {
print("Two numbers are equal") // prints "Two numbers are equal\n"
}
On the other hand, two instances are identical if they refer to the same instance of memory. Identity is used to determine whether two reference types are identical. The === operator is used to check for identity. The following example presents identity checking for two instances of the User class that we defined earlier:
let tarang = User(name: "Tarang")
let sangeeth = User(name: "Sangeeth")
if tarang === sangeeth {
print("Identical")
} else {
print("Not identical")
}
The preceding code example prints Not identical.
The identity checking operator is available only for reference types.