- Abstraction
- AI Pair Programming
- Algorithm
- API
- Array
- Array methods
- Booleans
- Callback
- Class
- Class Members
- Closure
- Closure
- Code refactoring
- Comment
- Computer programming
- Conditional statements
- Constant
- Constructor
- Coupling and Cohesion
- Data types
- Debugging
- Decorator
- Dependency
- Destructuring
- Dictionary
- Enum
- Event
- Exception / Error handling
- Function
- Generic / Template
- Higher-order function
- IDE
- Immutability
- Inheritance
- Input validation
- Integer
- Interface
- Iteration patterns
- Legacy code
- Loop
- Machine learning
- Memoization
- Memory and references
- Method
- Module
- Null / Undefined / None
- Null safety / Optional values
- Object
- Object-Oriented Programming (OOP)
- Operator
- Parameter
- Parsing
- Promise and Async/Await
- Prompt Engineering
- Recursion
- Regular expression
- Return statement
- Rollback
- Runtime
- Scope
- Script
- Sequence
- Set
- Spaghetti code
- Spread and Rest operators
- State management
- String
- Switch statement
- Synchronous vs Asynchronous execution
- Syntax
- Technical debt
- Ternary operator
- Testing
- This / Self
- Tuple
- Type casting
- Type conversion
- Variable
- Vibe coding
- Webhook
PROGRAMMING-CONCEPTS
Enum: Definition, Purpose, and Examples
An enum (short for enumeration) is a data type that defines a small, fixed set of related values. Instead of scattering loose strings or numbers across your codebase, an enum groups values under a single, explicit type. This makes your code more readable, reduces mistakes caused by typos, and clarifies the intent behind each value.
Enums show up everywhere — user roles, API statuses, UI themes, request methods, file permissions, days of the week, and many other concepts where only a limited number of valid values should exist.
What an Enum Represents
Enums model a controlled vocabulary within your program. When a variable uses an enum, it can only be one of the defined options.
For example, to represent directions:
- north
- south
- east
- west
Using strings makes mistakes easy:
movePlayer("nroth"); // typo
With an enum, invalid values are impossible because the compiler (or interpreter) enforces correctness.
You aren’t just storing text; you’re building a type that describes what values are allowed.
Enums in TypeScript
TypeScript supports numeric and string enums. Most developers prefer string enums because they’re easier to debug and safer to compare.
Numeric Enums
enum Status {
Pending,
Success,
Error
}
let current: Status = Status.Success;
TypeScript assigns numeric values automatically (Pending = 0, Success = 1, etc.).
This saves typing, but debugging may be less friendly because values appear as numbers.
String Enums
enum Role {
Admin = "ADMIN",
Member = "MEMBER",
Guest = "GUEST"
}
String enums avoid numeric confusion and are ideal for UI logic, logging, and API calls because the value is human-readable and predictable.
Using an Enum in Control Flow
function canAccess(role: Role) {
return role === Role.Admin;
}
canAccess(Role.Member); // false
The function only accepts valid roles. Typing "admin" accidentally is impossible — you must use the enum member.
Why TypeScript Enums Help
Without enums, you might write:
function canAccess(role: string) { ... }
This accepts anything, including "admni".
Enums prevent these silent, hard-to-debug bugs.
Enums in Python
Python includes enums through the Enum class.
Python
from enum import Enum
class Status(Enum):
PENDING = "pending"
SUCCESS = "success"
ERROR = "error"
Each value becomes a unique, immutable member of the Status type.
Comparisons become safer because only enumerated values are legal.
Using a Python Enum in Logic
Python
def handle(status: Status):
if status is Status.SUCCESS:
return "Done"
is ensures identity comparison — only the exact enum member matches.
Using strings would risk typos or mismatches in capitalization.
Enums in Swift
Swift’s enum system is expressive and widely used to model state.
Basic Swift Enum
enum Direction {
case north, south, east, west
}
Each direction is a distinct member of the Direction type.
Trying to assign an unsupported direction results in a compile-time error.
Associated Values in Swift
Swift offers a unique feature: enum cases can store data.
enum NetworkResult {
case success(data: String)
case failure(error: String)
}
This models branching states cleanly.
success carries returned data, while failure carries a specific error message.
It removes the need for parallel fields like:
// Not ideal:
struct Result {
let success: Bool
let data: String?
let error: String?
}
Swift enums prevent invalid combinations and force you to handle each case explicitly.
When to Use an Enum
Enums shine when your program needs to represent a stable, finite set of options.
1. Modeling Application States
Loading indicators, network statuses, and onboarding flows are perfect for enums.
For example:
LoadingSuccessError
Using enums forces the UI to handle each state intentionally.
2. Avoiding Typos and Logic Bugs
Without enums:
if (state === "Succcess") // typo
This silently fails.
Enums remove this entire category of errors.
3. Making Code Easier to Read
Enums give you self-documenting code:
var theme: Theme = .dark
vs.
var theme = "dark" // allowed to be "drak" or "yellow"
4. Improving Type Safety
Enums prevent invalid assignments:
let t: Theme = "blue"; // ❌ error
The compiler ensures correctness before the code ever runs.
Real-World Examples of Enums
These examples include short explanations to justify why enums fit each situation.
Example 1: UI Themes (TypeScript)
enum Theme {
Light = "light",
Dark = "dark"
}
function applyTheme(t: Theme) {
document.documentElement.dataset.theme = t;
}
applyTheme(Theme.Dark);
The enum ensures that the data-theme attribute is always "light" or "dark".
If someone tries to pass anything else, TypeScript stops the error before runtime.
Example 2: API State Handling (Swift)
enum ApiState {
case loading
case success(data: String)
case failure(message: String)
}
API states often require handling different types of information.
Swift enums with associated values allow expressive, structured branching.
Rendering UI Based on an Enum
func render(state: ApiState) {
switch state {
case .loading:
print("Loading...")
case .success(let data):
print("Data:", data)
case .failure(let message):
print("Error:", message)
}
}
The switch must cover all enum cases. This prevents missing logic paths.
Example 3: Order Processing Pipeline (Python)
Python
from enum import Enum
class OrderStatus(Enum):
NEW = 1
PROCESSING = 2
SHIPPED = 3
DELIVERED = 4
def can_ship(status: OrderStatus):
return status is OrderStatus.PROCESSING
The order can only be shipped from the PROCESSING state.
Enums make that rule explicit and enforceable.
Example 4: Building Dropdown Options (TypeScript)
enum LogLevel {
Info = "info",
Warn = "warn",
Error = "error"
}
const options = Object.values(LogLevel);
Object.values(LogLevel) generates a safe, complete list for forms, UI menus, and validation.
Example 5: React UI filter tabs (TypeScript)
enum Filter {
All = "ALL",
Active = "ACTIVE",
Completed = "COMPLETED"
}
function TaskFilter({ current }: { current: Filter }) {
return <div>Current filter: {current}</div>;
}
Filter values must match the set of UI tabs exactly.
Enums protect the component from receiving unsupported values.
Enums vs Objects, Constants, and Dictionaries
It may be tempting to use plain objects, keys, or strings.
Enums remain the stronger choice when relationships matter.
Objects
- Simple, flexible, easy to create
- Not type-safe
- Any incorrect key is silently accepted
Constants
- Good for single-purpose use
- No built-in relationship between values
Enums
- Model a type
- Restrict valid values
- Give structured intent
- Work with tooling, IDEs, autocomplete, and compilers
Enums exist to express certainty and enforce correctness.
Common Mistakes with Enums
Mistake 1 — Using enums for dynamic values
If values change (e.g., categories from an API), enums restrict flexibility.
Mistake 2 — Overusing enums
If there are only two values and they don’t represent a conceptual “type,” a boolean or simple constant may be clearer.
Mistake 3 — Mixing numeric and string enums
TypeScript numeric enums behave differently and can implicitly convert to numbers.
Mistake 4 — Forgetting switch coverage
Swift and TypeScript won’t allow missing enum branches.
This is good, but beginners often forget it.
Summary
An enum represents a fixed, meaningful set of values under a single type. It prevents mistakes, improves readability, and makes your program easier to understand. TypeScript uses enums to strengthen UI and API logic. Python’s Enum class groups constants into safe, comparable values. Swift takes enums further with associated data, making them a powerful modeling tool for complex application states.
Enums are the right solution whenever your application deals with controlled sets of values — roles, statuses, modes, categories, themes, directions, or processing states. They make your intent clear and your code significantly safer.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.