0
0
Swiftprogramming~5 mins

Identity comparison (===) in Swift

Choose your learning style9 modes available
Introduction

Identity comparison checks if two variables point to the exact same object in memory. It helps us know if they are truly the same instance, not just equal in value.

When you want to check if two class instances are the same object.
When comparing references to see if they share the same memory address.
When you want to avoid duplicating work by confirming if two variables refer to one object.
When debugging to understand if two variables point to the same instance.
When managing resources that should only exist once in memory.
Syntax
Swift
object1 === object2

The === operator works only with class instances (reference types).

It returns true if both variables refer to the same object, otherwise false.

Examples
personA and personB point to the same object, so identity comparison is true. personC is a different object.
Swift
class Person {}

let personA = Person()
let personB = personA
let personC = Person()

print(personA === personB)  // true
print(personA === personC)  // false
All variables point to the same Car instance, so identity comparison returns true.
Swift
class Car {}

let car1 = Car()
let car2 = car1
let car3 = car2

print(car1 === car3)  // true
book1 and book2 are two different instances, so identity comparison returns false.
Swift
class Book {}

let book1 = Book()
let book2 = Book()

print(book1 === book2)  // false
Sample Program

This program creates three Dog instances. dog1 and dog2 point to the same object, so identity comparison is true. dog3 is a different object even though the name is the same.

Swift
class Dog {
    var name: String
    init(name: String) {
        self.name = name
    }
}

let dog1 = Dog(name: "Buddy")
let dog2 = dog1
let dog3 = Dog(name: "Buddy")

print(dog1 === dog2)  // true
print(dog1 === dog3)  // false
OutputSuccess
Important Notes

Identity comparison (===) is different from equality comparison (==), which checks if values are equal.

Only class instances can be compared with ===, not structs or enums.

Summary

Identity comparison checks if two variables point to the exact same object.

Use === with class instances to compare their identity.

It returns true if both refer to the same object, otherwise false.