Class Vs Struct with Example in Swift

Anjali Joshi
3 min readSep 20, 2021

--

In this article, we will be learning the similarities and differences between Class and Struct.

First, let’s focus on the similarities:

  1. Both can define properties and functions.
  2. Both define initializers to setup initial state using init()
  3. Both can be extended using extension.
  4. Both can conform protocols.
  5. Both can work with generics.

The most important difference between Struct and Class is:

Classes are reference types whereas Structs are value types.

Let’s understand by an example.

Example of Class

In the above code, I have created a class called Flower which has two properties : color and noOfPetals.

Next, I created an instance of the class called periwinkle. This will assign the properties of the class to the periwinkle. So, when we print the properties of periwinkle, we will get the output as red and 5.

In the next line, I created a copy of periwinkle instance and named as sunflower. So, when we print the properties of sunflower, we will get the same output.

Now, let’s change the values of the properties of the sunflower instance. I have set the color as yellow and noOfPetals as 10.

Print the properties of sunflower instance again. You will notice the new values will be printed on console.

Now, let’s print the properties of periwinkle instance again. You will notice that the values of periwinkle instance will also be changed.

You must get the final output as displayed below:

Console Output of Class Example

When you copy a reference type, each instance shares the data. Hence, when you change one, the other changes too. That’s why, when we changed the values of the sunflower instance, the values of periwinkle instance also changed. This is how reference type works.

Now, let’s replace class by struct as shown in the below image.

Example of Struct

Run the code and have a look at the output.

Console Output of Struct Example

In the above output, you can see that even if the values of the sunflower instance is changed, the values of periwinkle instance still remains the same i.e red and 5. The periwinkle instance is not affected by the changed values of sunflower instance.

In value type, when you copy a value, an instance is created keeping its unique copy. If you change one instance, other doesn't change.

This is how Class and Struct work i.e reference type and value type work.

--

--