Skip to content

When to use Struct? When to use Class?

Struct in Swift

1. Value Type

Structs are value types, which means they are copied when passed around. Each instance maintains its own copy of data.

2. Immutability

  1. Structs can be made immutable,
  2. It's useful for creating thread-safe code
  3. Ensuring data consistency

3. No Inheritance

Structs do not support inheritance. You can’t create a subclass of a struct.

4. Automatic Initializer

Swift automatically provides an initializer for structs, making them easier to instantiate with member values.

Class in Swift

1. Reference Type

  1. Classes are reference types, meaning instances share a single copy of data.
  2. Modifying one reference affects all references to the same instance.

2. Mutability

Classes can have mutable properties, allowing in-place modification of data.

3. Inheritance

  1. Classes support inheritance, enabling you to create a class hierarchy with shared behavior and properties.
  2. Example: UIView

4. Deinitializers

  1. Classes can have deinitializers.
  2. Instance can be deallocated, useful for cleanup tasks.

Let's grow together 🌱

Cheers 🍻