Reference Type VS Value Type -Swift
// Tip From WriterWhen i encounter with an unexpected result while testing my code , i am always starting with "print(result)". So i do highly recommend that!
If you have not read my previous post about “Class VS Struct -Swift” yet, please go and read it first before that.
Let’s start with between difference them, reference types share a single copy of their data while value types keep a unique copy of their data. In swift reference type is as a class, value type is as a struct.
Reference Type’s : (Class, Function, Closure)
When we initializing an object, Ram allocates memory space and address to it. And, assigns it is memory address id to the object we created.
Each instance’s share a single copy of the main data.
Let’s create a Bird class, create instance from it and copy that main instance reference.
Value Type’s : (Struct, Array, Dictionary, Set, Enum, Tuple, String, Int, Double)
Value type is a whose value is copied when it is assigned to a variable or constant. Each instance’s keeps a unique copy of its own data.
As I mentioned above when we are initializing an object, Ram allocates memory space and address to it. There is 2 memory allocation area in RAM called by Heap and Stack. This is so important! and we need to know more about it.
Stack area used for static memory allocation, Heap area for dynamic memory allocation.
STACK : Value Types (Struct, Array, Dictionary, Set, Enum, Tuple)
Variables allocated on the stack are stored directly to the memory and access to this memory is very fast.
Stack is always reserved in LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from it stack is nothing more than adjusting one pointer. It is very fast.
HEAP : Reference Types (Class, Closure, Function)
Heap doesn’t automatically destroy its object like the stack does. Swift uses ARC (Automatic Reference Counting). Reference count is tracked by the ARC and when it becomes zero, the object is deallocated from memory.
But there is more we need to know about ARC.
Since the concepts of Arc and Reference count are too wide. My next article will be about ARC.
I hope this article was helpful.
References :