What if you could stop worrying about typos and missing cases when handling fixed options in your code?
Why Enum declaration and cases in Swift? - Purpose & Use Cases
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.
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.
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.
let fruit = "apple" if fruit == "apple" { print("It is an apple") } else if fruit == "banana" { print("It is a banana") }
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")
}
Enums enable you to clearly define and manage a fixed set of related options, making your code more reliable and easier to understand.
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.
Enums group related values under one type.
They reduce errors by limiting possible values.
They make code easier to read and maintain.