Enumerations
Swift offers another valuable structure, the Enum
. While enumerations are a common feature of programming languages, Swift's Enum
offers very much more than a simple mapping of integer values to labels.
Firstly, in cases where there is no logical mapping of Enum
values to integers (or values of any other type), we can declare an Enum
to be a type in its own right:
enum Color { case red case amber case green }
So, here we have a case in which it would be nonsensical to map colors to integers. Swift will not allow us to try to derive some integer value from Color.red
, either.
Note that the Enum
name is capitalized, whereas a case
is written in lowercase.
Note
This was not the case (no pun intended) in previous versions of Swift--another thing to be wary of when reading older posts, tutorials, and documentation.
There are, however, frequent uses for an Enum
that do correspond to some underlying value, and Swift lets us do this, too:
enum Medal: Int { case gold ...