Better Programming

Advice for programmers.

Follow publication

Member-only story

Classes vs. Structs in Swift — Basics and Memory Management

Neel Bakshi
Better Programming
Published in
7 min readMar 25, 2021

--

Photo by Fotis Fotopoulos on Unsplash.

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:

  1. Structures are value types, whereas classes are reference types.
  2. 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.

--

--

Neel Bakshi
Neel Bakshi

Written by Neel Bakshi

Guy who handles everything mobile @headout among other things! Ex @practo

Write a response