[Swift] Struct vs Class Which One is Better?

As same as structure in other OOP languages such as C, C++, etc, structure of swift is quite similar. However, swift structure evolved itself.

Structure looks like class, but obviously those are different and each has its own pros and cons.

1. Inheritance

Inheritance is the class' own feature. Structure cannot get a super struct.

2. Stack vs Heap

What is stack and heap? It's a kind of different way to store data. For instance, RAM and Hard Drive have different ways to save data.

Stack is kind of stack your books(data) one by one with order,  in the other hands, heap is just a random way to put books in the place.

Struct live on the stack  and Class live on the heap. When you retrieve struct, it has a reference, but class data is allocated into heap. Therefore, heap data is stacked for creating a reference finding a class data.

3. Struct is Value type and Class is Reference Type

Struct is a value type so it has its own data. However, Class is a reference type. It only has references to go to heap and find the data

For example, when you copy the struct, you will create a new value of data, while copying a class means copying an instruction for how to locate the block of memory inside the heap

This is a really important concept. If you copy the struct and change a variable data in the original struct, your copied struct will not be affected, However, when you do this same action into a class, your copied class variable will be changed its value.

Leave a Comment

ko_KRKorean