class Person { var name: String init(name: String) { self.name = name } } let p1 = Person(name: "Alice") let p2 = Person(name: "Alice") let p3 = p1 print(p1 === p2) print(p1 === p3)
The operator === checks if two variables refer to the same instance.
Here, p1 and p2 are two different instances with the same content, so p1 === p2 is false.
p3 is assigned to p1, so both refer to the same instance, making p1 === p3 true.
=== in Swift.=== works with in Swift.The identity operator === only works with class instances (reference types) to check if they point to the same object.
It does not work with value types like structs, integers, or strings.
if a === b cause a compile error?struct Point { var x: Int var y: Int } let a = Point(x: 1, y: 2) let b = Point(x: 1, y: 2) if a === b { print("Same") } else { print("Different") }
The identity operator === only works with reference types (classes).
Structs are value types, so you cannot use === with them.
class Box { let value: Int init(_ value: Int) { self.value = value } } let box1: Box? = Box(10) let box2: Box? = Box(10) let box3: Box? = box1 let box4: Box? = nil print(box1 === box2) print(box1 === box3) print(box1 === box4)
=== works with optionals by unwrapping them and comparing references.box1 and box2 are different instances, so box1 === box2 is false.
box3 points to the same instance as box1, so box1 === box3 is true.
box4 is nil, so box1 === box4 is false.
arr contain?class Node {} let n1 = Node() let n2 = Node() let n3 = n1 let n4 = n2 let n5 = Node() let arr = [n1, n2, n3, n4, n5]
n1 and n3 refer to the same instance.
n2 and n4 refer to the same instance.
n5 is a new instance.
So, the unique instances are: n1/n3, n2/n4, and n5 — total 3.