0
0
Swiftprogramming~5 mins

Identity operators (=== and !==) in Swift

Choose your learning style9 modes available
Introduction

Identity operators check if two variables point to the exact same object in memory. They help you know if two references are identical, not just equal.

When you want to check if two variables refer to the same instance of a class.
When comparing objects to avoid duplicate processing of the same instance.
When you want to ensure two references are not just equal in value but actually the same object.
When managing resources or caches where object identity matters.
When debugging to confirm if two references point to the same object.
Syntax
Swift
object1 === object2
object1 !== object2

Use === to check if two references point to the same object.

Use !== to check if two references point to different objects.

Examples
personA and personB point to the same object, so === returns 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
car1 and car2 are different objects, so !== returns true and prints the message.
Swift
class Car {}

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

if car1 !== car2 {
    print("Different cars")
}
Sample Program

This program creates three book references. book1 and book2 point to the same object, so === is true. book3 is a different object with the same content, so === is false and !== is true.

Swift
class Book {
    let title: String
    init(title: String) {
        self.title = title
    }
}

let book1 = Book(title: "Swift Basics")
let book2 = book1
let book3 = Book(title: "Swift Basics")

print(book1 === book2)  // true
print(book1 === book3)  // false
print(book1 !== book3)  // true
OutputSuccess
Important Notes

Identity operators only work with class instances, not with structs or enums.

Use equality operators (==) to compare values, identity operators (===) to compare references.

Summary

=== checks if two references point to the same object.

!== checks if two references point to different objects.

Use identity operators only with class instances, not value types.