Concept Flow - Identity comparison (===)
Create Object A
Create Object B
Compare A === B?
Yes→Same Object
No
Different Objects
This flow shows creating two objects and then checking if they are exactly the same object in memory using ===.
class Person {} let p1 = Person() let p2 = p1 let p3 = Person() print(p1 === p2) print(p1 === p3)
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create p1 as new Person() | p1 points to Object1 | p1 -> Object1 |
| 2 | Assign p2 = p1 | p2 points to same Object1 as p1 | p2 -> Object1 |
| 3 | Create p3 as new Person() | p3 points to Object2 | p3 -> Object2 |
| 4 | Evaluate p1 === p2 | Are p1 and p2 same object? | true |
| 5 | Evaluate p1 === p3 | Are p1 and p3 same object? | false |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| p1 | nil | Object1 | Object1 | Object1 | Object1 |
| p2 | nil | nil | Object1 | Object1 | Object1 |
| p3 | nil | nil | nil | Object2 | Object2 |
Identity comparison (===) checks if two variables point to the exact same object in memory. Use === only with class instances (reference types). If two variables refer to the same object, === returns true. If they refer to different objects, even if identical in content, === returns false. Useful to check object identity, not equality of content.
=== operator check in Swift?====== operator in Swift is used to check if two references point to the exact same object in memory.==, which checks if values are equal, === checks identity, meaning the same instance.a and b are identical in Swift?===.if a === b { }. The other options are either value equality, assignment, or invalid syntax.class Person {}
let p1 = Person()
let p2 = p1
let p3 = Person()
print(p1 === p2)
print(p1 === p3)p2 is assigned to p1, so both point to the same object. p3 is a new instance.p1 === p2 is true because they are the same instance. p1 === p3 is false because they are different instances.class Car {}
let car1 = Car()
let car2 = Car()
if car1 == car2 {
print("Same car")
}== unless the class conforms to Equatable.== without Car conforming to Equatable, causing a compile error.newObj is already stored in the cache by identity. Which Swift code correctly checks this?class Data {}
var cache: [String: Data] = [:]
let newObj = Data()
// Check if newObj is already in cache by identity=== inside a closure with contains(where:).cache.values.contains(where: { $0 === newObj }). if cache.values.contains(newObj) { print("Found") } uses contains without identity check, which requires Equatable. if cache.keys.contains(where: { $0 === newObj }) { print("Found") } incorrectly checks keys (strings) with identity. if cache.values.contains(where: { $0 == newObj }) { print("Found") } uses == which needs Equatable.Pass the test and this pattern moves unknown