April 30, 2020

Value type and Reference type in iOS swift.

By Mohit Agrawal

Difference between value type and reference type.

If you are an iOS developer and still confused about the difference between value type and reference type then you are at the right place because I am going to explain each and every topic in every detail. so let’s get started.

As we know that whenever we create an instance it gets saved to memory. A fixed memory address will be allocated to that instance. Now my question is what will happen when we create another copy of the same instance? Will a newly created instance will be allocated to the same memory address or will it get a different memory address? No need to worry this is where value type and reference type comes in the picture.

Value Type

The type of memory allocation where all the instances have their own unique copy of data. It means whenever we create a copy of instance then the newly created instance will be getting different memory addresses.

let a = 10
let b = a
value type

As you can see in the above example, I am creating a copy of “a” variable i.e is “b”. Both instances have a unique address, so even if we change the value of any one instance then the value of another one will be unaffected. Examples of value types are struct, int, string, bool, array, dictionary.

Reference type

The type of memory allocation where the instances share a single copy of the data. Examples are class, closures. Suppose if we create a copy of an instance then the newly created instance will use the same memory address as the old one. Both the instances will share the same memory address, only the pointers will be different. Let’s understand this by a simple example.

class A {
   var someValue = 20
}

let a = A()
let b = a
reference_type

In the above example, I have created a copy of class A to a new variable b. As you can see in the above image both sharing the same memory address (0x0002121) but with two different pointers. This type is known as the reference type. Now let’s see what will happen if change the value of b.

class A {
   var someValue = 20
}

let a = A()
let b = a
b.someValue = 10
reference_type

Did you notice the difference? Now the new value in the memory 0x0002121 will be 10. So it means even if you print a.someValue it will come 10 instead of 20. It is happening because both a and b are reference types and share the single copy of data.

Check out more interesting posts like this:

Asynchronously display data from API call in iOS

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!