THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
In Swift, there are two equal operator types.
==
,!=
) checks if two objects contains equal data or not.===
,!==
) checks if two objects reference is same or not.
Here is an example of primitive types22 === 1 // false
22 === 22 //true
22 == 1 // false
22 == 1 // false
==
checks the values are same, ===
checks values and reference type are same.
Let’s see examples of identical operators for objects and references. Next, create an object of a class and contains id, name properties
class Student: Equatable {
let id: Int
let name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
static func == (one: Student, two: Student) -> Bool {
return one.id == two.id
}
}
In this created three variables (s1,s2) of a class.
Two objects(s1,s2) are created with same data The third object(s3) is a variable, reference to an object(s2), s3 and s2 are pointed to the same object.
s1==s2 : returns as both objects contain the same data s1===s2 : returns false as both objects’ references are different. s2===s3: return true as both references to the same object.
let s1 = Student(id: 1, name: "abc")
let s2 = Student(id: 1, name: "abc")
let s3=s2;
print(s1==s2) // true
print(s1===s2) // false
print(s2===s3) // true
print(s1===s3) // false
Double equal | Triple Equal |
---|---|
` | ==, !=` are operators |
Checks for data is same | Checks both objects contain the same data and same memory location |
Value comparision | Reference comparision |
Similar to == in Objective C | Similar to isEqual in Objective C |
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts