0
0
Swiftprogramming~30 mins

Identity comparison (===) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Identity comparison (===) in Swift
📖 Scenario: Imagine you have two boxes that can hold toys. Sometimes, you want to check if both boxes are actually the same box, not just two boxes with the same toys.
🎯 Goal: You will create two class instances representing boxes and use identity comparison === to check if they are the exact same box.
📋 What You'll Learn
Create a class called Box with a property toy of type String
Create two variables box1 and box2 as instances of Box
Create a third variable box3 that points to the same instance as box1
Use identity comparison === to check if box1 and box2 are the same instance
Use identity comparison === to check if box1 and box3 are the same instance
Print the results of both comparisons
💡 Why This Matters
🌍 Real World
Identity comparison helps when you want to know if two variables refer to the exact same object, like checking if two references point to the same user profile in an app.
💼 Career
Understanding identity comparison is important for Swift developers working with classes, memory management, and reference types to avoid bugs and write efficient code.
Progress0 / 4 steps
1
Create the Box class and two instances
Create a class called Box with a property toy of type String. Then create two variables called box1 and box2 as instances of Box with toys "Car" and "Car" respectively.
Swift
Need a hint?

Define the class with a property and initializer. Then create two instances with the same toy name.

2
Create a third variable pointing to the first instance
Create a variable called box3 and assign it to the same instance as box1.
Swift
Need a hint?

Assign box3 to box1 to make them point to the same box.

3
Compare box1 and box2 using identity comparison
Use identity comparison === to check if box1 and box2 are the same instance. Store the result in a variable called sameBox1and2.
Swift
Need a hint?

Use === to compare if two variables point to the same instance.

4
Compare box1 and box3 and print results
Use identity comparison === to check if box1 and box3 are the same instance. Store the result in a variable called sameBox1and3. Then print both sameBox1and2 and sameBox1and3.
Swift
Need a hint?

Compare box1 and box3 with === and print both results to see which boxes are the same.