Skip to main content

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.

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.
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.
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).
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.
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.
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.
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.
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.
// 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>)
}
Master Swift with Deep Grasping Methodology!Learn More