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.
In this page:
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
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
}
let expression = ArithmeticExpression.addition(.number(3), .number(4))
print(expression)
Login to try C/C++/Java/PHP code in the editor
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
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))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
indirectkeyword on a case (or the whole enum) that refers back to itself; without it, Swift can't compute a fixed size for the type. - Confusing
indirect case(marks one case as needing indirection) withindirect enum(marks the whole enum), both are valid depending on need. - 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. indirecttells 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: