What’s the difference between == and === ?
What’s the difference between == and === ?
In Swift, == and === are used to compare values, but they serve different purposes and are used in different contexts.
== OperatorThe == operator is used to check if two values are equal. This is a value comparison, meaning it checks if the data or content of the two variables is the same. It can be used with both value types (like Int, Double, Struct, etc.) and reference types (like Class).
Example:
let a = 10
let b = 10
if a == b {
print("a and b are equal")
}
In this example, a and b are both integers with the same value, so a == b evaluates to true.
=== OperatorThe === operator is used to check if two references point to the same instance of a class. This is a reference comparison, meaning it checks if the two variables refer to the exact same object in memory. It is only applicable to class instances, not value types.
Example:
class Car {
var model: String
init(model: String) {
self.model = model
}
}
let car1 = Car(model: "Toyota")
let car2 = car1
let car3 = Car(model: "Toyota")
if car1 === car2 {
print("car1 and car2 refer to the same instance")
}
if car1 !== car3 {
print("car1 and car3 ...
junior