> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Enum

An enumeration (`enum`) in Swift is a first-class value type that defines a common type for a finite group of related values. Functioning as algebraic data types (specifically, sum types), Swift enums do not require a default integer backing value. They support advanced features typically reserved for classes and structs, including computed properties, instance methods, protocol conformance, and extensions.

## Basic Syntax

Enums are declared using the `enum` keyword. Individual values are defined using the `case` keyword. Multiple cases can appear on a single line, separated by commas.

```swift theme={"dark"}
enum CompassPoint {
    case north
    case south
    case east
    case west
}

enum Planet {
    case mercury, venus, earth, mars
}
```

## Associated Values

Swift enums can store heterogeneous data alongside distinct cases, acting as tagged unions. The type of the associated value can vary for each case.

```swift theme={"dark"}
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

// Instantiation
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
```

Associated values are extracted using pattern matching, typically within a `switch` statement, by binding the associated values to constants (`let`) or variables (`var`).

```swift theme={"dark"}
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
```

## Raw Values

Enums can be prepopulated with default values (raw values) of a uniform type. When declared with a raw value type, the **enum itself** implicitly conforms to the `RawRepresentable` protocol. The specified raw value type (such as `String`, `Character`, `Int`, or `Float`) must be `Equatable` and conform to the appropriate literal-convertible protocol (e.g., `ExpressibleByStringLiteral` or `ExpressibleByIntegerLiteral`). This allows the compiler to synthesize the raw values and the `init(rawValue:)` initializer.

```swift theme={"dark"}
enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}
```

### Implicit Raw Values

When using integers or strings as raw values, Swift can implicitly assign the values. For integers, the values auto-increment from `0` (or from a specified starting value). For strings, the implicit raw value is the text of the case name.

```swift theme={"dark"}
enum Month: Int {
    case january = 1, february, march, april
}
// Month.february.rawValue == 2

enum CompassDirection: String {
    case north, south, east, west
}
// CompassDirection.north.rawValue == "north"
```

### Raw Value Initialization

Enums with raw values automatically gain a failable initializer that takes a `rawValue` parameter and returns an optional of the enum type.

```swift theme={"dark"}
let possibleMonth = Month(rawValue: 3) // Returns Optional<Month>.some(.march)
let invalidMonth = Month(rawValue: 13) // Returns nil
```

## Methods and Computed Properties

Because enums are first-class types, they can define computed properties and methods. They cannot, however, contain stored properties outside of associated values.

```swift theme={"dark"}
enum TrafficLight {
    case red, yellow, green
    
    // Computed Property
    var isSafeToProceed: Bool {
        self == .green
    }
    
    // Mutating Method
    mutating func next() {
        switch self {
        case .red:
            self = .green
        case .yellow:
            self = .red
        case .green:
            self = .yellow
        }
    }
}
```

## Recursive Enumerations

Because enums are value types, their memory footprint must be known at compile time. A recursive enum (an enum that has another instance of the enum as the associated value for one or more of its cases) would theoretically require infinite memory.

To resolve this, Swift uses the `indirect` keyword, which instructs the compiler to allocate the associated value on the heap via a pointer, rather than inline.

```swift theme={"dark"}
// Applied to a specific case
enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}

// Applied to the entire enum
indirect enum LinkedList<T> {
    case empty
    case node(value: T, next: LinkedList<T>)
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
