Thursday, October 31, 2019

What’s the difference between == and === in Swift? (== vs ===)

Swift provides us two equality operators, == and ===, which are slightly different from each other. 
==  operator is used for comparing values whether they are equal. It is used for built in types such as strings, booleans, integers and doubles. For instance 4==4 is true, because 4 is equal to 4. 
=== operator is used for comparing references whether they point the same instance (same memory), it is identity operator. It is available only when using classes. 


Example:
Let’s declare a Student class like below:


class Student : Equatable {
    let id: Int
    let name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }

    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.id == rhs.id
    }
}


And let’s create two students which references to Student class and compare them using equal (==) and identical (===) operators. 


let studentA = Student(id: 1, name: "Edy")
let studentB = Student(id: 1, name: "Edy")


When we run below if condition we will see that they are equal.


if studentA == studentB {
  print("The two instances are equal")
}


The output will be:
The two instances are equal


Let’s check whether they are identical (===)


if studentA === studentB {
  print("The two instances are identical")
} else {
  print("The two instances are NOT identical")
}


The output will be:
The two instances are NOT identical


They are not identical because they reference two different instances in Heap area. 


If we create another instance based on one of these instances (studentA or studentB) and compare them we will see that they are identical. 


let studentC = studentA

if studentA === studentC {
  print("The two instances are identical")
} else {
  print("The two instances are NOT identical")
}


The output will be:


The two instances are identical


This means that they reference to the same point in the memory.




No comments:

Post a Comment