When is it better to use a class, and when is a structure in Swift?
2 answers
The main difference is that structures are passed by value, and classes by reference. From a performance point of view, it is important that instances of structures can be created on the stack, and instances of classes on the heap only.
According to The Swift Programming Language :
Structures are suitable if one or more conditions are met:
- Encapsulate a small set of simple values.
- Values should be copied, not passed by reference.
- The properties of the structure itself are value-types, which are also passed by value.
- Structures do not inherit properties or behavior.
Good examples:
- The size of the figure: width and height.
- Point in the space: x, y and z type double.
In most cases, you should use classes.
I suggest asking myself such questions:
1) Do I need inheritance?
2) Should I use class generics ('class SomeClass: ClassName')?
3) Will it be necessary for the instance of the object to be accessible from several places and can be changed from them. (object by reference, instead of copying)?
4) Do I need an initializer?
If there is no answer to all, then use the structure.