Struct vs Class
Value Semantics vs Reference Semantics
The core difference is copying behavior: a struct instance is duplicated when assigned or passed around, while a class instance is shared by reference.
Example: Value Semantics vs Reference Semantics
struct ValueBox { var content: Int }
class ReferenceBox { var content: Int; init(content: Int) { self.content = content } }
var v1 = ValueBox(content: 1)
var v2 = v1
v2.content = 2
print("Struct copies: v1=\(v1.content), v2=\(v2.content)")
let r1 = ReferenceBox(content: 1)
let r2 = r1
r2.content = 2
print("Class shares: r1=\(r1.content), r2=\(r2.content)")
Login to try C/C++/Java/PHP code in the editor
Choosing Between Struct and Class
Structs are usually preferred for simple data models without identity, while classes suit cases needing shared mutable state, reference identity, or inheritance.
Note: A good rule of thumb: start with a struct, and only switch to a class if you have a specific reason to need reference semantics.
Example: Choosing Between Struct and Class
struct Coordinate { let lat: Double; let lon: Double }
let home = Coordinate(lat: 40.0, lon: -75.0)
print("Home at \(home.lat), \(home.lon)")
Login to try C/C++/Java/PHP code in the editor
- Defaulting to
classfor everything out of habit from other languages; Swift and Apple's own guidance favor structs unless reference semantics or inheritance are specifically needed. - Not realizing structs support protocols and extensions just like classes, without needing inheritance.
- Forgetting only classes support inheritance from another class; structs cannot inherit from another struct.
- Structs are value types (copied on assignment); classes are reference types (shared on assignment).
- Only classes support inheritance from another class.
- Structs cannot deinitialize with
deinit; only classes can, since only they have a lifecycle tied to references. - Apple recommends preferring structs by default, using classes when shared mutable state or inheritance is genuinely needed.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: