← Back to Swift Course | Chapter 10: Enums | Lesson 6 of 6

Recursive Enums

A recursive enum is one that can contain another copy of itself inside it, like a set of nested boxes each holding a smaller box.

Declaring a Recursive Enum

Marking a case indirect allows it to hold another instance of the same enum, enabling recursive, tree-like structures.

Example: Declaring a Recursive Enum

markup
indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
}
let expression = ArithmeticExpression.addition(.number(3), .number(4))
print(expression)

Evaluating a Recursive Enum

A recursive function that mirrors the enum's structure can walk through nested cases, evaluating them down to a final result.

Example: Evaluating a Recursive Enum

markup
indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
}
func evaluate(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case .number(let value):
        return value
    case .addition(let left, let right):
        return evaluate(left) + evaluate(right)
    }
}
let expression = ArithmeticExpression.addition(.number(3), .addition(.number(4), .number(5)))
print(evaluate(expression))
Common Mistakes
  1. Forgetting the indirect keyword on a case (or the whole enum) that refers back to itself; without it, Swift can't compute a fixed size for the type.
  2. Confusing indirect case (marks one case as needing indirection) with indirect enum (marks the whole enum), both are valid depending on need.
  3. Writing a recursive function over a recursive enum without a proper base case, causing infinite recursion.
Chapter Summary
  • A case that contains the enum's own type as an associated value must be marked indirect.
  • indirect tells Swift to store that case's data via a pointer instead of inline.
  • Recursive enums are perfect for modeling nested structures like arithmetic expressions or linked lists.
  • Functions processing a recursive enum typically use recursion themselves, matching each case.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.