How it works...

We've already covered how value types differ from reference types; now, let's examine why they behave differently.

When storing new instances of a type in memory, Swift has two different data structures that it can use for storage: the Stack and the heap. These structures are common to many programming languages. Value types are stored on the Stack, and reference types are stored on the heap. Understanding how data is stored in these structures, even at the superficial level that we will cover, it will help us understand why value types and reference types have differing behavior.

The stack can be thought of as sequential blocks of data; an instance of a type may be represented by multiple blocks of data, and an instance can ...

Get Swift 4 Programming Cookbook 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.