Difference between == and ===
swift
Solution
In short:
`==` operator checks if their instance values are equal, `"equal to"`
`===` operator checks if the references point the same instance, `"identical to"`
Long Answer:
Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. Class references stay in Run Time Stack (RTS) and their instances stay in Heap area of Memory. When you control equality with `==` it means if their instances are equal to each other. It doesn't need to be same instance to be equal. For this you need to provide a equality criteria to your custom class. By default, custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator `==` and “not equal to” operator `!=` . To do this your custom class needs to conform `Equatable` protocol and it's `static func == (lhs:, rhs:) -> Bool` function
Let's look at example:
class Person : Equatable {
let ssn: Int
let name: String
init(ssn: Int, name: String) {
self.ssn = ssn
self.name = name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.ssn == rhs.ssn
}
}
`P.S.:` Since ssn(social security number) is a unique number, you don't need to compare if their name are equal or not.
let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")
if person1 == person2 {
print("the two instances are equal!")
}
Although person1 and person2 references point two different instances in Heap area, their instances are equal because their ssn numbers are equal. So the output will be `the two instance are equal!`
if person1 === person2 {
//It does not enter here
} else {
print("the two instances are not identical!")
}
`===` operator checks if the references point the same instance, `"identical to"`. Since person1 and person2 have two different instance in Heap area, they are not identical and the output `the two instance are not identical!`
let person3 = person1
`P.S:` Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.
if person3 === person1 {
print("the two instances are identical!")
}
They are identical and the output will be `the two instances are identical!`
Problem
In swift there seem to be two equality operators: the double equals (`==`) and the triple equals (`===`), what is the difference between the two?