Structs Are Always Copied
Earlier we talked about how structs are always copied when they are passed around. Let’s take a look at an example that proves this, using the Point
struct because it’s super simple:
var point1 = Point(x:10, y:10)
Now you can create point2
and assign it to point1
:
var point2 = point1
You modify point2
:
point2.x = 20
Now point1
and point2
are different:
point1.x // 10point2.x // 20
If point1
and point2
were classes, you would not get different values because classes are passed by reference.
Get Learning Swift™ Programming 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.