Swift Tutorial · Collections and Types · Lesson 14 of 30

Swift Classes and Reference Types

Classes, initializers, inheritance, reference semantics, and when to choose a class over a struct.

Create a free account to save this page, take notes and track your progress. Sign in

Reference semantics

Class instances are shared: two variables can refer to the same object, and a change through one is seen through the other. === checks whether two references point to the same instance. Classes support inheritance; mark a class final to prevent it.

Classes, inheritance and shared references
class Account {
    let owner: String
    private(set) var balance: Double

    init(owner: String, balance: Double = 0) {
        self.owner = owner
        self.balance = balance
    }

    func deposit(_ amount: Double) { balance += amount }
}

final class SavingsAccount: Account {
    let rate: Double
    init(owner: String, rate: Double) {
        self.rate = rate
        super.init(owner: owner)
    }
    func addInterest() { deposit(balance * rate) }
}

let a = Account(owner: "Ana")
let sameAccount = a
sameAccount.deposit(50)
print(a.balance, a === sameAccount)

let s = SavingsAccount(owner: "Ben", rate: 0.1)
s.deposit(200)
s.addInterest()
print(s.owner, s.balance)

Output

50.0 true
Ben 220.0

Run this on your computer — see “Get Started” for setup.

Struct or class?

Use a struct by default. Use a class when you need shared, mutable identity (a cache, a connection, an object observed by several screens) or inheritance from a framework class.

Value vs reference semantics
struct ValueCounter { var count = 0 }
final class RefCounter { var count = 0 }

var v1 = ValueCounter()
var v2 = v1
v2.count += 1

let r1 = RefCounter()
let r2 = r1
r2.count += 1

print("struct: \(v1.count) \(v2.count)")
print("class:  \(r1.count) \(r2.count)")

Output

struct: 0 1
class:  1 1

Run this on your computer — see “Get Started” for setup.

Test yourself

What does the === operator compare?

  1. Values for equality
  2. Whether two references point to the same class instance
  3. Types
  4. Hash values
Show answer

Answer: Whether two references point to the same class instance

Was this page helpful?