← Back to Swift Course | Chapter 10: Enums | Lesson 1 of 6

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.

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

markup
enum Direction {
    case north, south, east, west
}
let heading = Direction.north
print(heading)

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

markup
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")
}
Common Mistakes
  1. Forgetting to prefix a case with a dot when using it, e.g. writing Direction.north fully every time instead of the shorter .north where the type is already known.
  2. Comparing enum cases with associated or raw values incorrectly using == without the enum conforming to Equatable when needed for custom types.
  3. 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 enum defines a fixed group of related, named cases.
  • Cases are accessed with dot syntax, like Direction.north or shorthand .north.
  • switch statements 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.