An enumeration (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.
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 theenum 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.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 theRawRepresentable 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 from0 (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 arawValue 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 theindirect keyword, which instructs the compiler to allocate the associated value on the heap via a pointer, rather than inline.
Master Swift with Deep Grasping Methodology!Learn More





