TExcelTAD
Home › Swift › Swift Classes

Swift Classes

A class is, like a struct, a blueprint that bundles properties and methods. The big difference is that classes are reference types: a variable does not hold the object itself, only a reference to it. Several variables can point at the same object. Classes also support inheritance and deinitializers, which structs do not.

Defining a class and creating objects

Unlike structs, classes get no memberwise initializer. Every stored property must either have a default value or be set in an init you write yourself.

swift · try it yourself
class BankAccount {
    let owner: String
    var balance: Double

    init(owner: String, balance: Double = 0) {
        self.owner = owner      // self.owner is the property, owner is the parameter
        self.balance = balance
    }

    func deposit(_ amount: Double) {
        balance += amount        // no `mutating` needed in a class
    }

    func summary() -> String {
        "\(owner): $\(balance)"
    }
}

let account = BankAccount(owner: "Hana", balance: 100)
account.deposit(25.5)
print(account.summary())
Hana: $125.5

Two things to notice:

  1. account is a let constant, yet we changed balance. For a class, let only fixes which object the constant refers to — the object's var properties can still change.
  2. Methods modify properties without the mutating keyword.

Objects are shared, not copied

Assigning a class instance to another variable copies the reference. Both names now lead to the same object:

swift · try it yourself
class Playlist {
    var songs: [String] = []
}

let morning = Playlist()
let shared = morning          // same object, two names

shared.songs.append("Sunrise")
morning.songs.append("Coffee Time")

print(morning.songs)
print(shared.songs)
print(morning === shared)     // identity check
["Sunrise", "Coffee Time"]
["Sunrise", "Coffee Time"]
true

The identity operators === and !== ask "are these the very same object?". That question does not exist for structs, because every struct value is independent.

Identity vs equality

== compares values and only works if the type adopts Equatable; === compares references. Two different objects can be equal without being identical:

swift · try it yourself
class Tag: Equatable {
    let name: String
    init(name: String) { self.name = name }

    static func == (lhs: Tag, rhs: Tag) -> Bool {
        lhs.name == rhs.name
    }
}

let a = Tag(name: "swift")
let b = Tag(name: "swift")
let c = a

print("a == b :", a == b)    // same contents
print("a === b:", a === b)   // different objects
print("a === c:", a === c)   // same object
a == b : true
a === b: false
a === c: true

Deinitializers

A class can define deinit, which runs automatically just before an object is destroyed. Swift destroys an object when the last reference to it disappears (you will learn the details in Memory Management & ARC).

swift · try it yourself
class TempFile {
    let name: String
    init(name: String) {
        self.name = name
        print("Created \(name)")
    }
    deinit {
        print("Deleted \(name)")
    }
}

var file: TempFile? = TempFile(name: "draft.txt")
print("Working…")
file = nil      // last reference gone → deinit runs
print("Done")
Created draft.txt
Working…
Deleted draft.txt
Done

Struct or class?

struct class
Kind Value type (copied) Reference type (shared)
Memberwise initializer Yes No — write init yourself
Inheritance No Yes
deinit No Yes
Changing properties in methods Needs mutating Allowed
let instance Fully frozen Reference fixed, var properties still changeable
Identity (===) No Yes

Tip: Use a class when something has a single identity that many parts of the program should share — a network session, a game character manager, a document open in an editor. Use a struct for plain data.

Note: You can mark a class final (final class Logger { … }) to forbid subclassing. It documents your intent and lets the compiler optimise method calls.

Test yourself

Which operator checks whether two variables refer to the same class instance?

  1. ==
  2. ===
  3. ~=
  4. is

let acc = BankAccount(...) — can you change acc.balance (declared var)?

  1. No, let freezes everything
  2. Yes, let only fixes which object acc refers to
  3. Only inside init
  4. Only if the class is final

What do classes NOT get automatically that structs do?

  1. Methods
  2. A memberwise initializer
  3. Properties
  4. The ability to conform to protocols