Wednesday, 31 July 2019

Difference between == and ===




https://stackoverflow.com/questions/24002819/difference-between-and

== operator checks if their instance values are equal, "equal to”.  Value equality
=== operator checks if the references point the same instance, "identical to"  Reference equality

=== : Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. 


let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")

if person1 == person2 {//We are checking values of that variables
   print("the two instances are equal!")
}

if person1 === person2 {//Reference types we are checking references here.
   //It does not enter here
} else {
   print("the two instances are not identical!")
}

=== operator checks if the references point the same instance, "identical to". Since person1 and person2 have two different instance in Heap area, they are not identical 

let person3 = person1

P.S: Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.
if person3 === person1 {
   print("the two instances are identical!")
}

Range Operators: 
Closed Range: 1…5 gives 1, 2, 3, 4 and 5
Half-Open Range: 1..< 5 gives 1, 2, 3, and 4
One- sided Range :  1… gives 1 , 2,3… end of elements.  ,  …2 gives beginning… to 1,2


No comments:

Post a Comment

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...