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.
In this page:
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
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")
Login to try C/C++/Java/PHP code in the editor
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
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)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting classes do NOT get an automatic memberwise initializer like structs do -- you must write your own
init. - Assuming assigning a class instance to a new variable copies it; classes are reference types, so both variables point to the same object.
- Confusing
==(value equality, needs custom implementation) with===(identity: are these the same object in memory).
Chapter Summary
- A
classis 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: