Skip to content
AgileLogics
5 min read

Structs vs Classes

Prerequisites: Classes and reference types

Choosing between a struct and a class is one of the most common design decisions in Swift.

The core difference, side by side

struct PointValue { var x = 0 }
final class PointRef { var x = 0 }

let v1 = PointValue()
var v2 = v1        // copy
v2.x = 10

let r1 = PointRef()
let r2 = r1        // same object
r2.x = 10

print(v1.x, v2.x)
print(r1.x, r2.x)
0 10
10 10

Real-world analogy: handing someone a photocopy of a document (struct) versus a link to a shared online document (class). They can scribble on the photocopy without affecting yours; edits to the shared document are seen by everyone.

Why Swift prefers structs

With value types, no other part of your program can change your copy behind your back. That makes code easier to reason about and much safer when running work concurrently. Swift's standard library is built almost entirely from structs and enums, and Apple's guidance begins:

Use structures by default.

It then lists the specific situations that call for a class, which the next section summarizes.

Copies are also cheaper than they look: large standard types such as Array, Dictionary, and String use copy-on-write, so the data is only duplicated if one copy is actually changed.

When to use a class

  • You need shared, mutable identity — one object that several parts of the program observe and update (for example, a download manager or a data store shared across screens).
  • You need inheritance from a class, including many Apple framework classes such as UIViewController.
  • You need deinit to release a resource.

Quick comparison

Struct Class
Assignment Copies the value Shares one instance
Memberwise initializer Automatic Write your own
Changing methods Need mutating Don't
Inheritance No (use protocols) Yes
deinit No Yes

Mark classes final unless you intend them to be subclassed — it states your intent and lets the compiler optimize method calls.