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 " }
On the other hand, two instances are identical if they refer to the same instance of memory. Identity is used to determine if 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 have defined earlier:
let julie = User(name: "Julie") let steve = User(name: "Steve") if julie === steve { print("Identical") } else { print("Not identical") }
The identity checking operator is available only for reference types.