What does it mean to control the identity of the data being modeled?

Viewed 210

I'm reading about when to choose structs over classes in Swift here on Apple's documentation. I'm a bit confused as to what they meant by the bullet point that reads:

  • Use classes when you need to control the identity of the data you're modeling

What does this mean?

2 Answers

Identity refers to === identity in data structures, so control of identity refers to the choice of data structure type.

  • Structs are local objects which have === identity, whereas instances of a class will not have === identity.
  • The data of a class can be referenced more specifically and more globally than the struct.

The more limited struct is the preferred model, and while the more complex class model is powerful, it is more error-prone.

This is for future folks, I had a great deal understanding this identity thing but the apple documentation was in quite simple terms.

"Control of identity" means control of reference. As stated in apple's documentation :

Classes in Swift come with a built-in notion of identity because they’re reference types. This means that when two different class instances have the same value for each of their stored properties, they’re still considered to be different by the identity operator.

But it also means that when you share a class instance across your app, changes you make to that instance are visible to every part of your code that holds a reference to that instance.

Hope this helps!!

Related