How to Pass a Variable as a Reference in Swift?
In Swift, types are categorized into two distinct categories. Reference Types and Value Types.
Reference Types
To keep it simple, a class
is always passed as a reference. In other words, only a single copy is maintained irrespective of how many places we pass the same object.
Look at the below code, we’ve defined a class Match
, which has a single property called score
. The code which we need to closely look at is from line 13 to 16, where we are
- Creating a
match
object with initialscore
value of 10. - Printing to see what
score
value holds before passing thematch
object, which is 10. - Passing the
match
object tofunc finish
, wherescore
is set to 100. - Printing to see what
score
value holds now, which is 100.
Initial State
Below image depicts a simplified version of Device RAM and how the match
object (at address 0111) holds it’s initial state with a score
value of 10 right after line 13 is executed.
Updated State
Once match object is passed to func finish
, the updated state of the match
object holding score
value of 100, right after line 15
is executed. Note that there’s only one copy of match
object is maintained in the RAM.
Value Types
A struct
is passed as a value, meaning multiple copies are created when the object is passed around. So, how do we achieve the same behaviour as it were a class
?
Simple, just use inout
parameter. Look at the example below, which is essentially the same as the above example but just class Match
is changed to struct Match
and a couple other changes to make use of inout
keyword.
We don’t need to look at any virtual device RAM diagram now because the above code with struct will produce same Initial state and Updated state as if it was a class
, and only maintain a single copy.
The key here are two things,
inout
keyword&
prefix while passing thematch
object, which is something the compiler will complain if we don’t add.
That’s it. Thank you for reading. Please drop a comment if you have any questions.