0
0
Swiftprogramming~3 mins

Why Enum declaration and cases in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop worrying about typos and missing cases when handling fixed options in your code?

The Scenario

Imagine you are writing a program to handle different types of fruits. You write separate variables or constants for each fruit type and then write many if-else checks everywhere to see which fruit you have.

The Problem

This manual way is slow and confusing. You might forget a fruit type or mistype a name. Adding a new fruit means changing many parts of your code, which can cause bugs and wastes time.

The Solution

Enums let you group related values under one name. You declare all possible cases once, and the compiler helps you use them correctly everywhere. This makes your code cleaner, safer, and easier to update.

Before vs After
Before
let fruit = "apple"
if fruit == "apple" {
    print("It is an apple")
} else if fruit == "banana" {
    print("It is a banana")
}
After
enum Fruit {
    case apple
    case banana
}
let fruit = Fruit.apple
switch fruit {
case .apple:
    print("It is an apple")
case .banana:
    print("It is a banana")
}
What It Enables

Enums enable you to clearly define and manage a fixed set of related options, making your code more reliable and easier to understand.

Real Life Example

Think of a traffic light system where the light can only be red, yellow, or green. Using enums, you can represent these states clearly and handle each case safely in your code.

Key Takeaways

Enums group related values under one type.

They reduce errors by limiting possible values.

They make code easier to read and maintain.