Difference between == and === in the swift example

In Swift, there are two equal operator types.

  • Double equal (==) and double not equal (!=) operator
  • Triple equal (===) and triple not equal (!==)operator

Swift Identity operator

  • Double equal operator(==,!=) checks if two objects contains equal data or not.
  • Triple equal operator(===,!==) checks if two objects reference is same or not. Here is an example of primitive types
22 === 1 // false
22 === 22 //true  
22 == 1 // false
22 == 1 // false

== checks the values are same, === checks values and reference type are same.

Let’s see examples of identical operators for objects and references. Next, create an object of a class and contains id, name properties

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

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

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

In this created three variables (s1,s2) of a class.

Two objects(s1,s2) are created with same data The third object(s3) is a variable, reference to an object(s2), s3 and s2 are pointed to the same object.

s1==s2 : returns as both objects contain the same data s1===s2 : returns false as both objects’ references are different. s2===s3 : return true as both references to the same object.

let s1 = Student(id: 1, name: "abc")
let s2 = Student(id: 1, name: "abc")
let s3=s2;
print(s1==s2) // true
print(s1===s2) // false
print(s2===s3) // true
print(s1===s3) // false

Difference between double and triple equal operators in Swift

Double equalTriple Equal
| ==, != are operators===, ,!== are operators
Checks for data is sameChecks both objects contain the same data and same memory location
Value comparisonReference comparison
Similar to == in Objective-CSimilar to isEqual in Objective-C