0
0
Swiftprogramming~3 mins

Why Raw values for enums in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop juggling confusing numbers and let your code remember them perfectly for you?

The Scenario

Imagine you have a list of colors, and you want to assign each color a number or a string to identify it. You write separate variables for each color and its value. When you want to check or use these values, you have to remember each one and write extra code to match them.

The Problem

This manual way is slow and confusing. If you add or change a color, you must update many places. It's easy to make mistakes, like mixing up numbers or forgetting to update a value. Your code becomes messy and hard to read.

The Solution

Using raw values for enums lets you group related values together with clear names and automatic links to their raw data. You write less code, avoid errors, and your program understands the connection between names and values easily.

Before vs After
Before
let red = 1
let green = 2
let blue = 3
// Need to remember these numbers everywhere
After
enum Color: Int {
    case red = 1
    case green = 2
    case blue = 3
}
// Use Color.red.rawValue to get 1
What It Enables

This makes your code cleaner and lets you easily convert between names and values, making your programs smarter and less error-prone.

Real Life Example

Think of a traffic light system where each light color has a number code. Using raw values in enums helps you manage these codes clearly and safely in your app.

Key Takeaways

Manual value management is slow and error-prone.

Raw values in enums link names to values automatically.

This simplifies code and reduces mistakes.