Class and Struct

Which one to use?

3/8/20242 min read

Struct and class structures are frequently used structures in Swift language. Although they are very similar to each other in structure, they also have different properties. In this article, we will talk about the similarities and differences between structs and classes.

Similarities:

Both are defined the same way. They have properties and methods.

It can be expanded with Extension. They can be used together with Protocol.

Differences:

The class structure expects us to create our own init method. Struct does this automatically.

If the Init method will not be defined in the class structure, values should be assigned to the variables in the class or defined as optional.

One of the most important differences between classes and structs is that classes are reference types, whereas structs are value types. This means that a class instance is stored as a pointer in memory and can be shared between variables or functions.

Output:

Structs are value types. This means that the values of a struct instance are stored directly in memory, and when copied to another variable a completely new instance is created.

Output:

Additionally, while classes can inherit, structs cannot.

As a result, we need to determine which one we should use based on these features of classes and structs. Structs are simpler and more efficient structures than classes. Swift documentation also recommends us to use struct for simple models. Depending on the project requirement and usage scenarios, we must decide whether we should use a Class or a Struct.