
A common question among beginners in iOS development is the difference between a class and a struct. After all, both can have initializers, be extended, implement protocols, and create instances with properties and methods. However, understanding their unique characteristics is essential for making the best choices in your code.
To start, a class is a reference type, meaning that when we instantiate a class, we create a reference to a memory address where that object is stored. On the other hand, a struct is a value type, meaning that when we instantiate a struct, we create a copy of that struct at a new memory address. I know this might sound a bit abstract, so let’s illustrate it with an example.
Real-World Analogy
Imagine you have a photo with your friends, and they all want to post it on Instagram. However, each friend wants to edit it differently. Knowing this, you send each friend a copy of the photo, and each one can edit it however they like.
Struct instances work the same way — each variable gets its own copy of the struct and can modify its values without affecting the others.
On the other hand, if you share an iCloud link to the photo with all your friends and one of them edits the image in the cloud, everyone will see the edited photo. This happens because they don’t have separate copies; instead, they are all accessing the same image in the cloud.
Class instances work this way — if multiple variables point to the same object and one modifies it, all others will reflect the change.
Class vs. Struct
A practical difference between a class and a struct is how instances are passed as parameters to a method. If it’s a struct instance, the method receives a copy of the struct. If it’s a class instance, the method receives a reference to the original object. This means that any changes made to a class instance inside the method will affect the original object outside of it.
Beyond instance sharing, classes support inheritance, allowing a subclass to inherit and modify the properties and methods of another class. Another unique feature of classes is the deinitializer (deinit), which enables us to manually free resources before Automatic Reference Counting (ARC) handles memory deallocation.
Unlike classes, structs do not support instance sharing, inheritance, or memory management features like deinitializers. Because of their simplicity, structs offer better performance and help prevent memory management bugs, such as retain cycles (which can lead to memory leaks).
Like everything in programming, both have advantages and disadvantages, and you should choose based on the needs of your project. To see these differences in code and deepen your understanding, check out the article Understanding Reference and Value Types in Swift.