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:
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
enum Direction {
case north, south, east, west
}
let heading = Direction.north
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
enum Direction {
case north, south, east, west
}
let heading = Direction.east
switch heading {
case .north:
print("Heading north")
case .south:
print("Heading south")
case .east:
print("Heading east")
case .west:
print("Heading west")
}
Login to try C/C++/Java/PHP code in the editor
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: