← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 2 of 9

Classes Basics

A class is like a struct's cousin -- also a blueprint for custom things -- but everyone who has a copy actually shares the exact same object.

Defining and Using a Class

A class groups properties and methods like a struct, but requires an explicit initializer to set up its stored properties.

Example: Defining and Using a Class

markup
class Car {
    var brand: String
    var speed: Int
    init(brand: String, speed: Int) {
        self.brand = brand
        self.speed = speed
    }
}
let myCar = Car(brand: "Toyota", speed: 0)
print("\(myCar.brand) at \(myCar.speed) mph")

Classes Are Reference Types

Assigning a class instance to another variable does not copy it; both variables refer to the exact same object, so changes through one are visible through the other.

Example: Classes Are Reference Types

markup
class Car {
    var brand: String
    var speed: Int
    init(brand: String, speed: Int) {
        self.brand = brand
        self.speed = speed
    }
}
let carA = Car(brand: "Honda", speed: 0)
let carB = carA
carB.speed = 60
print("A speed: \(carA.speed), B speed: \(carB.speed)")
Common Mistakes
  1. Forgetting classes do NOT get an automatic memberwise initializer like structs do -- you must write your own init.
  2. Assuming assigning a class instance to a new variable copies it; classes are reference types, so both variables point to the same object.
  3. Confusing == (value equality, needs custom implementation) with === (identity: are these the same object in memory).
Chapter Summary
  • A class is declared much like a struct but is a reference type.
  • Classes must define their own initializer; there's no automatic memberwise init.
  • Assigning a class instance shares the same underlying object between variables.
  • === checks whether two references point to the exact same instance.
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.