tezvyn:

Swift Enums: Type-Safe Choice Modeling

AI-drafted, machine-checkedintermediate

A Swift enum is a closed menu of possibilities the compiler tracks exhaustively. Use it to replace string constants or model a network result state. Adding a case without updating every switch breaks compile-time safety if you rely on a default clause.

WHY IT EXISTS: Before enums, developers used raw integers or strings to represent distinct states, which meant any value was legal even if it made no sense. Swift enums solve this by creating a closed set of named cases so the compiler can prove you have handled every possibility. This turns runtime crashes into compile-time errors.

THE MENTAL MODEL: Think of an enum as a vending machine button panel. Only the installed buttons exist; you cannot invent a new one at runtime. Each button represents a distinct choice, and pressing one means the machine knows exactly what to do next without guessing.

HOW IT WORKS: You declare an enum with the enum keyword followed by a name and a set of cases. Each case can stand alone or carry associated values, which let you attach extra data without creating separate structs. You can also assign raw values like integers or strings for serialization. Swift requires switch statements to be exhaustive, meaning every case must be addressed or a default must be provided. Because enums are first-class types in Swift, they can have methods, computed properties, and protocol conformances just like structs and classes.

WHEN TO USE IT: Use enums whenever a variable should only hold one value from a fixed list. Common examples include result states like success and failure, view controller modes like edit and readOnly, or finite options like compass directions. They shine when you need to attach heterogeneous data to each case, such as a success case carrying a user model and a failure case carrying an error code.

WHEN NOT TO USE IT: Do not use an enum when the set of values is open-ended or user-defined, because adding a new case requires recompiling the module. Avoid them when you need reference semantics or inheritance hierarchies; structs and classes are better suited. Also skip enums if you find yourself stuffing every case with identical associated values just to satisfy the type system, since that usually signals a modeling mistake.

ONE CANONICAL EXAMPLE: A network request result is the classic Swift enum pattern. You define enum NetworkResult with a success case that carries a Data payload and a failure case that carries an Error. The caller switches on the result and the compiler forces handling of both branches. If you later add a cached case, every switch statement without a default clause produces a build error, preventing silent omissions.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.