Identity vs. Equality

Now that you understand the difference between value and reference types, you are ready to learn about equality and identity. Equality refers to two instances having the same values for their observable characteristics, such as two instances of the String type that have the same text. Identity, on the other hand, refers to whether two variables or constants point to the same instance in memory. Take a look at this sample code.

let x = 1
let y = 1
x == y // True

Two constants, x and y, are created. They are both of type Int and hold on to the same value, 1. Not surprisingly, the equality check, done via ==, evaluates to true. This makes sense because x and y hold on to exactly the same value.

This is exactly ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.