Swift Tutorials: Identity Operators (===, !==) 🚀

beginner
22 min

Swift Tutorials: Identity Operators (===, !==) 🚀

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Swift's Identity Operators - === and !==. Let's learn these powerful tools that help us compare values and objects in Swift. 🎯

What are Identity Operators?

Identity Operators are used to compare whether two variables or constants hold the exact same memory location. They help us check if the variables are pointing to the same instance or not. 📝

Equality Operator (==) vs Identity Operator (===)

Swift has two operators to check for equality:

  1. Equality Operator (==): It checks if the values of two variables are the same.
  2. Identity Operator (===): It checks if the two variables are the same instance, i.e., if they refer to the same memory location.

📝 Note:

  • The Equality Operator (==) is used for comparing values, such as numbers, strings, and Booleans.
  • The Identity Operator (===) is used for comparing objects, like classes, structures, and enumerations.

When to use Identity Operator?

Use the Identity Operator (===) when you want to compare object instances. This is particularly useful in situations where you want to ensure that two variables refer to the same object, such as when dealing with mutable objects in a function or method. 💡

Syntax and Examples

Here's the syntax for using Identity Operators:

swift
let variable1 = SomeObject() // SomeObject is a class, structure, or enumeration let variable2 = SomeObject() // Compare the objects if variable1 === variable2 { print("Both variables point to the same instance.") } else { print("Both variables do not point to the same instance.") }

Complete Working Example

Let's create a simple Person class and see Identity Operators in action:

swift
class Person { var name: String init(name: String) { self.name = name } } // Create two instances of Person let person1 = Person(name: "John") let person2 = Person(name: "John") // Check if they are the same instance (they're not) if person1 === person2 { print("person1 and person2 are the same instance.") // This won't print } else { print("person1 and person2 are not the same instance.") // This will print } // Now let's make person1 and person2 refer to the same instance let person3 = person1 // Check if they are the same instance (now they are) if person1 === person3 { print("person1 and person3 are the same instance.") } else { print("person1 and person3 are not the same instance.") // This won't print }

Quiz

Quick Quiz
Question 1 of 1

What is the main purpose of the Identity Operator in Swift?

Now that you've learned about Swift's Identity Operators, you're one step closer to mastering Swift's object comparison mechanisms. Keep up the great work, and happy coding! 🤖