How to Pass a Variable as a Reference in Swift?

Akshit Zaveri
The Startup
Published in
2 min readFeb 21, 2021

In Swift, types are categorized into two distinct categories. Reference Types and Value Types.

Photo by Anton Darius on Unsplash

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

  1. Creating a match object with initial score value of 10.
  2. Printing to see what score value holds before passing the match object, which is 10.
  3. Passing the match object to func finish, where score is set to 100.
  4. 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,

  1. inout keyword
  2. & prefix while passing the match 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.

--

--

Akshit Zaveri
The Startup

Passionate iOS Applications Engineer,  fan. I mostly write about tech.