Enum cases can contain one or more payloads (associated values):
The payload must be provided when instantiating the enum value:
The switch statement can extract the associated value:
A single case extraction can be done using if case:
The guard case syntax can be used for later use extraction:
Enums with associated values are not Equatable by default. Implementation of the == operator must be done manually:
Normally, enums can't be recursive (because they would require infinite storage):
The indirect keyword makes the enum store its payload with a layer of indirection, rather than storing it inline. You can use this keyword on a single case:
indirect also works on the whole enum, making any case indirect when necessary:
Enums can have custom init methods that can be more useful than the default init?(rawValue:). Enums can also store values as well. This can be useful for storing the values they where initialized with and retrieving that value later.
Using that initializer we can do this:
You can nest enumerations one inside an other, this allows you to structure hierarchical enums to be more organized and clear.
And you can use it like that:
Raw and Hash values
Enums without payloads can have raw values of any literal type:
Enums without any specific type do not expose the rawValue property
Integer raw values are assumed to start at 0 and increase monotonically:
String raw values can be synthesized automatically:
A raw-valued enum automatically conforms to RawRepresentable. You can get an enum value's corresponding raw value with .rawValue:
You can also create an enum from a raw value using init?(rawValue:):
If you wish to get the hash value of a specific enum you can access its hashValue, The hash value will return the index of the enum starting from zero.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0