Recursive Enumerations

You now know how to attach associated values to enum cases. This brings up a curious question. Can you attach an associated value of an enum’s own type to one of its cases? (Perhaps this question brings up another: why would you want to?)

A data structure that comes up frequently in computer science is a tree. Most hierarchical data can naturally be represented as a tree. Think of a family tree: it contains people (the “nodes” of the tree) and ancestral relationships (the “edges” of the tree). The family tree branching stops when you reach an ancestor you do not know, as in Figure 14.2.

Figure 14.2  A family tree

Modeling a family tree can be difficult because for any given person, you may know ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.