Swift Basics: Struct vs Class
structs
and classes
form the foundation of Swift language. Lot of developers face difficulty in comprehending the usage of struct and classes. If you are facing this difficulty, you have come to the right place. Lets get the basics right.
When asked about structs and classes, any developer would answer Structs are value types and Classes are reference type. So what does this actually mean?
Lets start with a real world example. It would provide more clarity on the concept.
Reference type: Ram and Shyam are collaborating remotely on a shared document with the content “Hello World”. Ram changes the content to “Hello Swift” on his machine and it is reflected on the Shyam’s machine. Similarly when Shyam makes any changes to the document content, it is immediately reflected on the Ram’s machine. This is because of both are referencing the same document.
Value type: Shyam saves Ram’s contact number on his phone. After reaching home, Shyam updates Ram’s contact number on his phone. But this will change only on Shyam’s phone and won’t have any effect outside of it. Which basically means they are two distinct copies.
In “value types”, (example: struct, enum, tuples) each instance keeps a unique copy of its data.
In “reference types”, (example: class) instances share a single copy of the data.
Design Class
Let’s design a class, DogClass
that has a name
property.
Lets create aDogClass
instance of DogClass with the name
property set to “A-Doggo”
Assign aDogClass
instance to newly created instance bDogClass
. Change the name
property of bDogClass
to “B-Doggo”
Let’s print the name
property of both instances.
The name
property of aDogClass
has been changed to "B-Doggo" as well. Which meant both instances were pointing to same object and any change in one instance would reflect on other instance. Hence class
are reference types.
Design Struct
Similar to DogClass
, let’s design a struct DogStruct
that has a name
property.
Note: In struct, init method is not necessary as it is generated automatically by the compiler.
Let’s create aDogStruct
instance of Dog struct with the name
property set to “A-Doggo”
Let’s assign aDogStruct
to bDogStruct
and change the name
property of bDogStruct
to “B-Doggo”.
Let’s print the name
property of both instances.
Printing names of both the instances reveals changing the name
property of bDogStruct
has no effect on aDogStruct
. This validates information was “copied” from aDogStruct
to bDogStruct
, maintaining a distinct copy. Since both the instances are unique, any changes in one of the instances wont affect the other. Hence struct
are value types.
Hidden Gem: When you assign an instance of a value type to a variable, a copy isn’t created in the first place. Rather, compiler optimizes by pointing it to the same instance. A new copy is created only when you mutate the variable. This compiler optimization is known as lazy copy or copy on write.
Below image shows the fundamental difference between value type and reference type.
Advantages of Value types over Reference types
- Efficiency: Value types are faster than Reference types. This can be owed to reference types as they are allocated on heap, which is expensive compared to stack allocation. Also, in order to free up the allocated memory OS needs to keep track of reference count and when count is zero the memory is freed. This overhead is not seen in value types leading to efficient instance creation and copy.
- Thread Safety: Value type instances are safe in a multi-threaded environment as multiple threads can mutate the instance without having to worry about the race conditions or deadlocks. Writing multi-threaded code with value types thus becomes simpler, safer and more efficient.
- No memory leaks: Value types have no references unlike reference types. Hence there is no overhead of memory leaks in value types.
When to use?
Use a value type when:
- You want copies to have independent state
- The data will be used in code across multiple threads
Use a reference type when:
- You want to create shared, mutable state.
Conclusion
We were able to identify :
- Why
struct
is a value types andclass
is a reference types. - Advantages of value types over reference types.
- What to choose,
struct
orclass
based on your needs.
That’s a wrap for now. :)
Thank you for reading! Feel free to comment or reach me on Twitter: @vinkini for any queries.
More where this came from
This story is published in Noteworthy, where thousands come every day to learn about the people & ideas shaping the products we love.
Follow our publication to see more product & design stories featured by the Journal team.