Difference between value type and a reference type in iOS swift?

This is one of the basics of every programming language. Most of us might have started programming with C language. If you still remember the function call by value and call by reference, you might get some idea about what this exactly is. let’s see what apple says about this.

Image for post
Image for post

Very basic definition:

Image for post
Image for post
Gif source: Internet

Let’s do some coding

Image for post
Image for post
reference types
Image for post
Image for post

Class is a reference type. Copying a reference, implicitly creates a shared instance. After a copy, two variables then refer to a single instance of the data, so modifying data in the second variable also affects the original.

Question: What happens if we change the var to let in the above code block?

let peterVilla = Home()
let johnVilla = peterVilla
Image for post
Image for post

What if johnVilla is a var??

Image for post
Image for post

What will happen if Home is a struct???

Image for post
Image for post
let peterVilla = Home()let johnVilla = peterVillajohnVilla = Home()//error: cannot assign to value: ‘johnVilla’ is a ‘let’ constant

Note: SO, For Value types , if we want to reassign the object or change the variable inside the object, it should be declared as mutable (‘var’).

Image for post
Image for post

Note: When you are mutating a value type in swift, you are not actually mutating the value. You are mutating the variable holding the value.

Image for post
Image for post

When do we choose a Value Type over a Reference Type?

Use a value type when:

Use a reference type (e.g. use a class) when:

How Reference and Value types are stored in memory ?

Differences between Stack and Heap!

In short: Reference types always goes to the Heap, whereas Value Types always go where they are declared.

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

iOS and tvOS developer, dreamer, photographer 🤨