DEV Community

Cover image for Swift: Understand Recursive Enum in Five Minutes
rathodmayur93
rathodmayur93

Posted on

Swift: Understand Recursive Enum in Five Minutes

1. What is the Recursive Enumeration

A recursive enumeration is an enumeration — short: an enum — that has another instance of the enum as the associated value.

2. How to define Recursive Enumeration case

You can indicate that an enum case is recursive by writing indirect before it. For example:

You can also write indirect before the beginning of the enum to enable indirection for all of the enumeration’s cases that have an associated value:

The above enumeration can store three kinds of arithmetic expressions: a plain number, the addition of two expressions, and the multiplication of two expressions. The addition and multiplication cases have associated values that are also arithmetic expressions

3. How to use Recursive Enumeration

To use the ArithmeticExpression enum will take a simple example of the arithmetic operation. We will calculate (5 + 4) * 3 expression value using recursive enum.

A recursive function is a straightforward way to work with data that has a recursive structure. For example, here’s a function that evaluates an arithmetic expression:

Complete Code:

I believe this is pretty straight forward. If, however you need any clarification or questions, leave me a comment below and I will get it answered. Thanks for reading.

You can also find this article on medium.

Top comments (0)