Understanding the difference, their purpose, benefits, and downsides.
In Swift, both structs and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You use them to create custom data types.
Struct Definition:
struct Resolution {
var width = 0
var height = 0
}
Class Definition:
class VideoMode {
var resolution = Resolution()
var frameRate = 0.0
var name: String?
}
This is the most fundamental difference between structs and classes.
Structs are Value Types:
Classes are Reference Types:
struct Point {
var x: Int
var y: Int
}
var point1 = Point(x: 1, y: 2)
var point2 = point1 // A copy is made
point2.x = 100
print(point1.x) // Output: 1
print(point2.x) // Output: 100
point1 remains unchanged because point2 is a separate copy.
class Person {
var name: String
init(name: String) { self.name = name }
}
var person1 = Person(name: "Alice")
var person2 = person1 // A new reference is made
person2.name = "Bob"
print(person1.name) // Output: "Bob"
print(person2.name) // Output: "Bob"
person1's name changes because both variables refer to the same object.
| Feature | Structs | Classes |
|---|---|---|
| Type | Value Type | Reference Type |
| Inheritance | Cannot inherit | Can inherit from other classes |
| Initializers | Automatic memberwise init |
Must create init manually |
| Deinitializers | Cannot have deinit |
Can have deinit |
| Mutability | let instances are immutable |
let instances can have mutable properties (if var) |
| Memory | Stored on the Stack (faster) | Stored on the Heap (slower, requires reference counting) |
Benefits:
Downsides:
Car is a Vehicle).Benefits:
deinit: Allows for custom cleanup logic when an object is destroyed.Downsides:
The Swift team at Apple provides a clear recommendation:
Start with a struct.
Use structs by default, especially for modeling data that doesn't have a distinct identity or lifecycle. Examples include coordinates (CGPoint), sizes (CGSize), or custom data models passed around your app.
Use a class only when you need features that structs don't provide:
deinit to manage a resource.For SwiftUI, this is even more true. Most of your data models should be structs.
Understanding this distinction is key to writing clean, safe, and efficient Swift code.