Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 146 ยท Structures, Classes and Enums

Classes

Learn Swift classes - reference semantics, initializers, shared mutable state, identity with ===, inheritance basics, deinit and ARC, and a clear guide to choosing a class or a struct.

A class looks very much like a struct: a name, some properties, some methods, an initializer. The difference is one idea that changes everything. A struct is a value: assigning it makes a copy. A class is a reference type: assigning it makes another name for the same object. Two variables can point at one instance, and a change made through either of them is visible through both.

That sharing is exactly what you want for some things (one window on the screen, one open database connection, one game character that many parts of the program refer to) and exactly what you do not want for others (a coordinate, a price). Swift lets you choose per type. This lesson shows how classes work, what the shared identity buys you and costs you, and gives a practical rule for choosing between a class and the struct you already know.

Declaring a class

The syntax is nearly the same as for a struct, with one visible change: a class does not get a free memberwise initializer. You must write init (or give every property a default value).

Swift A first class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at what is missing compared with a struct. addPoints changes score and is not marked mutating: a method on a reference type can always change the object's properties, because the method receives a reference, not a copy. And ada is a let constant yet we changed its score. We will explain why in a moment.

Forgetting the initializer is the first error most people see with classes:

Swift A class without an initializer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: class 'Player' has no initializers, with notes that the stored properties name and score have no initial value and so prevent synthesized initializers (a second error, 'Player' cannot be constructed because it has no accessible initializers, points at the call). Either write init(name:score:) that assigns every stored property, or give each property a default (var score = 0) and then Player() works. The memberwise initializer exists for structs only.

Reference semantics: one object, many names

Now the central experiment. We create one player and give it a second name:

Swift Two names for one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Assigning first to second copied only the reference. Changing second.value changed the single underlying object, so first.value shows 42 as well. The function bump modified an object that belongs to its caller, something a struct parameter could never do without inout. The array team holds three references, two of them to the same object, so editing team[0] also changed second.

Compare with the struct version of the same code:

Swift The same experiment with a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Same shape, opposite behaviour. Knowing which behaviour a type has is a core part of reading Swift code, which is why the language makes you write struct or class at the declaration. Value vs. Reference Semantics takes the comparison further.

let with a class: the reference is constant, the object is not

Earlier, let ada = Player(...) did not stop ada.addPoints(...). For a class, let means the reference cannot be changed to point at a different object. The object itself is still free to change its var properties.

Swift Reassigning a let reference (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first assignment works; the last one produces error: cannot assign to value: 'box' is a 'let' constant. Use var for a reference you intend to repoint. Remember the contrast: with a struct, let makes the entire value immutable.

Identity versus equality

Two different kinds of "the same" exist for objects, and Swift gives each its own operator:

  • Identity (===, !==): do these two references point at the same object? Only for classes.
  • Equality (==): do these two values mean the same thing? You decide, by conforming to Equatable.
Swift === versus ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Identity is how you ask "is this the very same window / connection / node?". Equality is how you ask "do these hold the same data?". Unlike structs, classes never get == synthesized: you must write it, and you should compare exactly the properties that define sameness.

Inheritance in a nutshell

Only classes can inherit. A subclass gets everything its superclass has and can add or replace behaviour. The full story is in Inheritance; here is the minimum:

Swift A tiny class hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The array has the type [Shape] but holds a Square, a Circle and a plain Shape. Calling describe() uses each object's real area(); that is dynamic dispatch, decided at run time by the object, not the variable. (The circle area uses 3 as an approximation of pi to keep the output short.) final marks a class that cannot be subclassed; use it by default, because it lets the compiler optimize calls and states your intent. Inheritance is one tool of several: Swift code tends to prefer protocols over class hierarchies.

Lifetimes: ARC and deinit

Objects are created with init and live on the heap. Swift frees an object automatically when nothing refers to it any more; it keeps a count of strong references (this is ARC, automatic reference counting) and destroys the object when the count reaches zero. A class can declare a deinit that runs just before that, which makes the lifetime visible:

Swift Watching an object die

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each close session line appears at the moment the last reference disappears: the end of the do block for session 2, the assignment of nil for session 3, and the end of the function for session 1. deinit is where a class releases non-memory resources (closing a file, unregistering an observer). Structs have no deinit.

ARC has one famous hazard: two objects that refer to each other strongly keep each other alive forever (a retain cycle). Breaking it needs a weak or unowned reference. That topic has its own lesson, Memory Management with ARC, so we only plant the flag here.

Classes and Swift 6 concurrency

Reference semantics means shared mutable state, and shared mutable state is what causes data races when several tasks run at once. Swift 6 therefore treats ordinary classes as not Sendable: they cannot simply be handed to another thread of execution. Structs made of Sendable values are Sendable automatically. This is one of the strongest practical reasons to prefer structs, and to wrap shared class state in an actor or protect it with a lock when you cannot avoid it. You will meet the rules in Sendable and Data Races. Here is the check in action; the program is the top-level code of main.swift, so tally belongs to the main actor:

Swift Sharing a class with another task (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Swift 6 refuses to compile it. The first error is non-Sendable type 'Tally' of let 'tally' cannot exit main actor-isolated context, with a note that class 'Tally' does not conform to the 'Sendable' protocol, followed by main actor-isolated let 'tally' cannot be accessed from outside of the actor. The same program with a struct compiles, because a copy is what crosses into the task:

Swift A Sendable struct crosses safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The task increments its own copy and returns 1, while the original is still 0; no data can be raced because nothing is shared.

Writing a copy method

If you need independent copies of a class instance, you have to build them yourself, because there is no automatic copying:

Swift Copying an object by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

alias sees the new tag, because it is the same object; duplicate does not, because copy() created a second object with its own array. Many bugs come from forgetting that let backup = document made no backup at all.

Struct or class? A practical rule

Start from a struct. Reach for a class when at least one of these is true:

  • Identity matters. The program must talk about the connection, the user session, the node in a graph, and several places must share and observe the same instance.
  • You need inheritance from a class, for instance when a framework requires you to subclass one.
  • You need deinit, to clean up when the last user goes away.
  • The data is big, shared and changes in one place, and copying would be wasteful or wrong.

Otherwise, a struct is simpler, safer for concurrency and often faster. A third option appears in the concurrency chapters: an actor is a reference type that protects its own state.

Feature struct class
Assignment copies the value copies the reference
Inheritance no yes
Memberwise init yes no, write init
Mutation of properties needs mutating and var always allowed on var properties
let instance whole value constant only the reference is constant
deinit no yes
Identity (===) no yes
Stored inline, often on the stack heap, reference counted

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given let a = Counter(); let b = a; b.value = 9 where Counter is a class, what is a.value?

    a and b refer to the same object, and let only fixes the reference, not the object's properties.
  2. 2. What does the === operator test?

    === is identity. == is equality, which you define by conforming to Equatable.
  3. 3. Why does a class need an explicit init when its properties have no defaults?

    Only structs receive the automatic memberwise initializer. A class must write init (or provide defaults for every property).
  4. 4. When does deinit run?

    ARC destroys the object when its strong reference count reaches zero and runs deinit just before freeing it.
  5. 5. Which situation points to a class rather than a struct?

    Shared identity and changing state are what reference types are for. Plain data values are usually structs.

Summary

  • A class is a reference type: assigning or passing it copies the reference, so all names refer to one shared object.
  • Classes need an explicit init (or defaults for all properties); there is no memberwise initializer.
  • Methods can change var properties without mutating; let on a class instance only fixes the reference.
  • === tests identity, == tests equality, and for classes you write == yourself.
  • Classes can inherit and override; mark them final unless you plan to subclass.
  • ARC frees an object when its last strong reference disappears, and deinit runs first; reference cycles need weak or unowned.
  • Swift 6 treats classes as non-Sendable by default, another reason to start with structs.
  • Choose a class for identity, inheritance or deinit; choose a struct for plain data.

Next: Properties