Reference and Value Types

Structures and classes are far more alike in Swift than they are in most languages. However, there is one major difference in how they operate: classes are reference types; structures, enums, and tuples are value types.

What does it mean to be a value type? For one thing, a value type is always treated as a single value, even if it is composed of several individual values via its properties.

In practical terms, this means that when a value type is assigned or passed as a parameter, a copy is made. The following code demonstrates the effect with the Vector structure:

v​a​r​ ​v​e​c​t​o​r​0​ ​=​ ​V​e​c​t​o​r​(​x​:​ ​0​,​ ​y​:​ ​0​)​ ​ ​ ​ ​ ​ ​ ​ ​v​e​c​t​o​r​0​ ​=​ ​{​x​ ​0​,​ ​y​ ​0​}​ v​a​r​ ​v​e​c​t​o​r​1​ ...

Get Cocoa Programming for OS X: 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.