← 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.
Syntax
swift
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

markup
// 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)

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
// 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")
}
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
  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.