Swift Enums & Pattern Matching

Swift Tutorial

🎯 Swift Enums & Pattern Matching – Complete Beginner to Advanced Guide

Enums (Enumerations) in Swift are extremely powerful.
When combined with pattern matching (switch, if case, guard case, where), they become one of Swift’s strongest features—and a top interview topic.


1️⃣ What is an Enum in Swift? ⭐

An enum defines a finite set of related values.


 

📌 Use enums instead of strings or integers for type safety.


2️⃣ Basic Enum Usage ⭐


 


3️⃣ Enums with Raw Values ⭐⭐

Enums can have raw values (String, Int, etc.).


 

Output

200

Raw Value Initialization


 

📌 Returns an optional (Status?)


4️⃣ Enums with Associated Values ⭐⭐⭐ (Very Important)

Enums can store values of different types.


 

Usage


 


5️⃣ Pattern Matching with switch ⭐⭐⭐


 

📌 switch on enums must be exhaustive


6️⃣ Pattern Matching with if case ⭐⭐


 

📌 Cleaner when you care about one case only.


7️⃣ Pattern Matching with guard case ⭐⭐⭐


 

📌 Very common in real-world Swift code


8️⃣ Enums with where Clause ⭐⭐⭐


 


9️⃣ Enums with Computed Properties ⭐⭐


 


🔟 Enums with Methods ⭐⭐


 


1️⃣1️⃣ Enums + Optionals (Special Case) ⭐⭐

Optional itself is an enum:


 

Pattern Matching Optional


 


1️⃣2️⃣ Tuple Pattern Matching ⭐⭐⭐


 


1️⃣3️⃣ fallthrough with Enums ⚠️


 

📌 Rarely recommended, but good to know.


1️⃣4️⃣ Enums vs Struct vs Class ⭐⭐

Feature Enum Struct Class
Finite states
Associated values
Value type
Inheritance

📌 Interview Questions (Enums & Pattern Matching)

Q1. Why enums are powerful in Swift?
👉 Associated values + exhaustive switch

Q2. What is pattern matching?
👉 Matching values against patterns (switch, if case)

Q3. Difference between raw values & associated values?
👉 Raw = fixed type, Associated = dynamic per case

Q4. Is Optional an enum?
👉 Yes


✅ Summary

✔ Enums model finite states
✔ Raw values give constants
✔ Associated values store data
✔ Pattern matching makes code safe & clean
switch must be exhaustive
if case / guard case simplify logic
✔ One of Swift’s most important interview topics

You may also like...