← 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.
Syntax
swift
class ClassName {
    var property: Type

    init(property: Type) {
        self.property = property
    }
}

let instance = ClassName(property: value)

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
// Define a class `Car`
class Car {
    var brand: String
    var speed: Int
    init(brand: String, speed: Int) {
        self.brand = brand
        self.speed = speed
    }
}
// Declare a constant `myCar`, set to `Car(brand: "Toyota", speed: 0)`
let myCar = Car(brand: "Toyota", speed: 0)
// Print "\(myCar.brand) at \(myCar.speed) mph" to the console
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
// Define a class `Car`
class Car {
    var brand: String
    var speed: Int
    init(brand: String, speed: Int) {
        self.brand = brand
        self.speed = speed
    }
}
// Declare a constant `carA`, set to `Car(brand: "Honda", speed: 0)`
let carA = Car(brand: "Honda", speed: 0)
// Declare a constant `carB`, set to `carA`
let carB = carA
carB.speed = 60
// Print "A speed: \(carA.speed), B speed: \(carB.speed)" to the console
print("A speed: \(carA.speed), B speed: \(carB.speed)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.