What is the difference between class, struct, and enum?

In Swift, classes, structs, and enums are key building blocks that enable developers to create complex data models. Here’s a brief overview of each:

  • Class: A reference type that can inherit from other classes. Instances of classes can be modified after they are created, and they support identity, meaning that two variables can refer to the same instance.
  • Struct: A value type that is copied when it's assigned or passed. Structs do not support inheritance and are more lightweight when compared to classes. They are ideal for simple data encapsulation.
  • Enum: A type that consists of a group of related values and enables you to work with those values in a type-safe way. Enums in Swift can also have associated values, allowing for more flexible data handling.

classes structs enums Swift programming reference type value type inheritance data encapsulation