Swift: Classes, Structures & Optionals
What you will learn
The difference between structs (value types) and classes (reference types), and how Swift handles optional values safely.
Structures (value types)
struct Person {
var name: String
var age: Int
}
var alice = Person(name: "Alice", age: 25)
var bob = alice // COPY — alice and bob are independent
bob.name = "Bob"
print(alice.name) // "Alice" — unchanged
Structs are value types: they are copied on assignment. let alice makes the struct immutable.
Classes (reference types)
class Animal {
var name: String
init(name: String) {
self.name = name
}
func speak() -> String {
return "..."
}
}
let dog = Animal(name: "Rex") // reference, even with let
let pet = dog // same object — both refer to Rex
pet.name = "Max"
print(dog.name) // "Max" — changed through pet
Classes are reference types: they are shared, not copied. let on a class reference prevents reassignment but the object's properties can still change (if var).
Struct vs Class — when to use what
| Struct | Class | |
|---|---|---|
| Type | Value (copied) | Reference (shared) |
| Inheritance | No | Yes |
| Mutability | let makes fully immutable |
let prevents reassignment, not mutation |
| Memory | Stack (usually) | Heap |
| Use for | Simple data types | Objects with identity |
Optionals (no null pointers)
Swift has no nil for regular types. Use Optionals to represent the absence of a value:
var name: String? = nil // Optional<String>, can be nil
name = "Alice"
// Optional binding — safe unwrapping
if let unwrapped = name {
print("Hello, \(unwrapped)!")
}
// Guard let — early exit
guard let name = name else { return }
print(name) // name is now a regular String
Common mistakes
- Forcing an optional with
!when you haven't checked for nil — causes a runtime crash - Using a class when a struct would be more efficient and safer
- Forgetting that
leton a class reference does not make the object immutable
Quick check below!