Member-only story
Classes vs. Structs in Swift — Basics and Memory Management
Value types vs. reference types, stack vs. heap allocation, and more
I’ve been asked this question many times during interviews: “What is a class and what is a struct? Mention a few differences and when you would use them.”
So I thought I would tackle this topic starting from the very basics and move on to each of their niche properties.
General Overview
At a very high level, structs and classes can be thought of as constructs that are used to hold values (variables and constants) and functions. The feature sets provided by each of them are similar, except for a few implementation details that actually contribute to your decisions on when to use a struct and when to use a class.
Structures differ from classes in two ways:
- Structures are value types, whereas classes are reference types.
- Structures do not support inheritance (essentially a consequence of the first point).
Value Types vs. Reference Types
In Swift, classes and closures are reference types, whereas structs and enums are value types.