Google News
logo
Swift - Interview Questions
What is the difference between the "==" operator and the "===" operator in ios Swift?
The fundamental difference between the "==" operator and the "===" operator in ios Swift is that the equal to "==" operator compares value types to see if the values are the same while the equivalent to "===" operator compares reference types to see if the references point to the same instance (both point to the same memory address) or not.  Let us consider the following example for understanding the difference between the two in a better way :
class Human: Equatable {
   let id: Int
   let nameOfPerson: String
   init(id: Int, nameOfPerson: String) {
       self.id = id
       self.nameOfPerson = nameOfPerson
   }
   static func == (left: Human, right: Human) -> Bool {
       return left.id == right.id
   }
}
let human1 = Human(id: 2, nameOfPerson: "Janvi")
let human2 = Human(id: 2, nameOfPerson: "Janvi")
 
Now, for the piece of code given below, we can say that the two human instances are equal since their id is the same. Therefore, "Equal Instances!" gets printed.
if human1 == human2 {
  print("Equal Instances!")
}else{
  print("Instances Not Equal!")
}
 
Now, for the piece of code given below, we can say that the two human instances are not equivalent even though their id is the same since they point to different areas in the Heap Area, that is, they point to different addresses. Therefore, "Instances are not Equivalent!" gets printed.
if human1 === human2 {
  print("Equivalent Instances!")
}else{
  print("Instances are not Equivalent!")
}
Advertisement