Swift - Struct vs Class
Struct:
- It has value semantics and hence variable and value is unified.
- Each instance can have only one owner
- The value held by a variable can not be manipulated without changing the variable itself
- Efficient compared to class due to copy on write and no involvement of retain count management
- A Code that uses struct without any of its members being reference type is easy to reason because ownership is clearly defined
- No memory leaks to deal with
- When a variable becomes immutable, the instance also becomes immutable and if a variable is mutable then the instance also becomes mutable when it has mutable variables or mutable methods.
Classes:
- The variable and instance are different and hence both can be manipulated separately
- Each instance can have more than one owner
- If an instance is amended, then all the references represented by different variables will be impacted
- When a variable holding reference is made as immutable only the reference the variable holds is immutable not the instance the reference is pointing to. To make a class instance immutable, all its stored properties must be immutable
Thanks to KHAWER KHALIQ for providing such comprehensive writing on structs vs classes