In swift types are split in 2 main categories:
- reference types
- value types
Classes are reference types; structs (which include arrays and dictionaries), basic data types (int, float, string, etc.), and enums are all value types.
A value type is always passed by value, which means when assigning to a variable or passing to a function/method, a copy of the original data is created. There's an exception to this rule: a function/method can use the inout
modifier on a value type parameter to have it passed by reference.
Note that the compiler and the runtime usually do optimizations, so a copy is not always created unless strictly needed - what's important is that we, as developer, know that we are working on a copy and not on the original data.
A reference type is always passed by reference, which means when assigning it to a variable or passing it to a function/method, a reference to the data and not the data itself is assigned/passed.
UIView
is a class, so when you create an instance, assign it to a variable, then assign that variable to another variable, the reference to the instance and not the instance itself is assigned. Both variables point to the same UIView
instance. Any change made to the instance is visible to all variables referencing that instance.
Suggested reading: Classes and Structures