← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 3 of 9

Struct vs Class

Structs are like handing someone a photocopy of your paper -- they get their own separate copy -- while classes are like handing someone the same original paper -- there's still only one.

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

markup
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)")

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

markup
struct Coordinate { let lat: Double; let lon: Double }
let home = Coordinate(lat: 40.0, lon: -75.0)
print("Home at \(home.lat), \(home.lon)")
Common Mistakes
  1. Defaulting to class for everything out of habit from other languages; Swift and Apple's own guidance favor structs unless reference semantics or inheritance are specifically needed.
  2. Not realizing structs support protocols and extensions just like classes, without needing inheritance.
  3. Forgetting only classes support inheritance from another class; structs cannot inherit from another struct.
Chapter Summary
  • 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:

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.