Skip to main content
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.

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.
Associated values are extracted using pattern matching, typically within a switch statement, by binding the associated values to constants (let) or variables (var).

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.

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.

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.

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.

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.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More