Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Recursive Enumerations in Swift
Written by Team Kodeco

A recursive enumeration is an enumeration that has a case that is associated with an instance of the enumeration. To declare a recursive enumeration, use the indirect keyword before the enumeration definition. Here is an example of a recursive enumeration that represents a simple arithmetic expression:

indirect enum ArithmeticExpression {
  case number(Int)
  case addition(ArithmeticExpression, ArithmeticExpression)
  case multiplication(ArithmeticExpression, ArithmeticExpression)
}

In this example, the ArithmeticExpression enumeration has three cases: number, addition, and multiplication. The number case is associated with an Int value, while the addition and multiplication cases are associated with instances of ArithmeticExpression.

You can use recursive enumerations in the same way as you use non-recursive enumerations. The only difference is that you can use an instance of the enumeration as the associated value of a case. Here is an example that creates an arithmetic expression that represents the sum of 2 and 3:

let two = ArithmeticExpression.number(2)
let three = ArithmeticExpression.number(3)
let sum = ArithmeticExpression.addition(two, three)

Recursive enumerations are particularly useful when working with tree-like data structures, such as expressions and hierarchies.

© 2024 Kodeco Inc.