What is the difference between Struct and Class?
As a programmer, we have no chance not to use Classes. Especially while developing iOS, we must have encountered Structs next to Classes. In Swift, we have to choose between these two. Most people would suggest you use struct over the Class as it is much more efficient and optimized. But is this the truth? Let’s examine for an answer to this question together.
First of all, let’s see a few differences between them in the below.
Let’s design an example Car Class that has an engine capacity.
Now in the below, we create an xCar instance of Car with the engineCapacity property set to “X-Car.
If we assign xCar instance to newly created instance yCar. We change the engineCapacity property of xCar to 2000.
Do you guess it what happens? In the below example, we can see in the logs printed in the console that xCar and yCar property after the lines has been executed, printed the same value both of them. That’s because they are class of reference type.
Now let’s design the same object with struct
In the above example, the Initial method is not necessary. It generates automatically by the editor. Now let’s again create an instance like xCar.
Let’s again assign xCar to yCar and change the engineCapacity property of yCar to 2000.
Let’s compile and look up console what happened.
The console output engineCapacity of both instances reveals changing the engineCapacity property of yCar does not affect xCar. This validates information was copied from xCar to yCar. Any changes in one of the instances won’t affect the other.
Value types are faster than Reference types. In addition, Value type instances are safe in multiple threads without race conditions or deadlocks. If you don’t need a shared, mutable state, you prefer Structs.