Enumerations as data structures
Although we have already seen in Chapter 2, BasicĀ Swift, that enum
in Swift goes a lot further than merely representing integers with more memorable symbols; we have only just scratched the surface. The enum
in Swift is so powerful that its use encroaches far into terrain that once belonged exclusively to heavyweight data structures such as classes.
Note
For that reason, enum
plays a huge part in Swift; give yourself some time to play around with them, and start to uncover the many ways in which they can offer a lightweight and clear option for structuring your data.
In this section, we'll look at three areas that are particularly powerful, one of which we might not expect to associate with an enum
:
- enum methods
- Associated types
- Recursive
enum
definitions
Adding methods to enums
The first feature of a Swift enum
that makes them so much more than just names of integer values (or any other type) is the ability to add methods to them.
Let us create an enum
of traffic...