Enum Basics
An enum lists out every possible option something could be, like the days of the week, so you can't accidentally pick something invalid.
In this page:
Syntax
enum EnumName {
case first, second, third
}
let value = EnumName.first
switch value {
case .first: /* code */
case .second: /* code */
case .third: /* code */
}
Defining an Enum
An enum declares a closed set of possible values with case, giving each option a clear, named identity.
Example: Defining an Enum
// Define an enum `Direction` listing its possible cases
enum Direction {
// Enum case(s): `north, south, east, west`
case north, south, east, west
}
// Declare a constant `heading`, set to `Direction.north`
let heading = Direction.north
// Print `heading` to the console
print(heading)
Login to try C/C++/Java/PHP code in the editor
Using switch with an Enum
Because switch requires exhaustiveness, matching an enum's cases is a natural fit and the compiler ensures every case is handled.
Example: Using switch with an Enum
// Define an enum `Direction` listing its possible cases
enum Direction {
// Enum case(s): `north, south, east, west`
case north, south, east, west
}
// Declare a constant `heading`, set to `Direction.east`
let heading = Direction.east
// Switch on `heading` and branch by case
switch heading {
// Case: `.north`
case .north:
// Print "Heading north" to the console
print("Heading north")
// Case: `.south`
case .south:
// Print "Heading south" to the console
print("Heading south")
// Case: `.east`
case .east:
// Print "Heading east" to the console
print("Heading east")
case .west:
print("Heading west")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to prefix a case with a dot when using it, e.g. writing
Direction.northfully every time instead of the shorter.northwhere the type is already known. - Comparing enum cases with associated or raw values incorrectly using
==without the enum conforming toEquatablewhen needed for custom types. - Treating an enum case as if it were a string constant; it's a genuinely distinct type-safe value, not just named text.
Chapter Summary
- An
enumdefines a fixed group of related, named cases. - Cases are accessed with dot syntax, like
Direction.northor shorthand.north. switchstatements pair naturally with enums since Swift can check exhaustiveness.- Enums are true value types with their own strict, type-safe identity.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: