You should know these 5 differences between a struct and a class in swift

Muhammad Abdullah
2 min readAug 25, 2019

--

  1. Initialiser

struct have by default initializer, while there is no default init in classes. The logic behind it could be because a struct is not subclassable, making it obvious that a complete initializer would be required, and as such it was made implicit by the language.

On the other hand, a class is subclassable, and as such, you may want to design it so that it can only be initialized from subclasses, and as such an implicit initializer was not provided by the language.

2) Mutating

Classes don’t enforce constants as strongly as structs — if a property is declared as a variable, it can be changed regardless of how the class instance was created.

3) Deinitialization

A struct is a value type and does not require memory management that would need a deinit. Structs are not independently persistent the way classes are. Merely setting a property of a struct destroys it and replaces it. Assigning a struct copies it. Structs are created and destroyed in a highly lightweight way. They don’t need to signal their destruction; they are too lightweight for that. Therefore, Deinitializers may only be declared within a class.

4) Inheritance

In swift classes support inheritance, while struct doesn’t. but classes can support single inheritance but no multiple inheritances.

5) Value type and reference types

In swift classes, the instance is a reference type, while struct’s instance is a value type.

source

--

--