Recursive enumerations let you create values that can contain other values of the same type. This helps model things like trees or nested lists easily.
Recursive enumerations in Swift
indirect enum EnumName { case simpleCase case recursiveCase(EnumName) }
The indirect keyword tells Swift that the enum can hold values of its own type.
You can mark the whole enum as indirect or just specific cases.
indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(ArithmeticExpression, ArithmeticExpression) }
node case is recursive, holding a value and the rest of the list.enum LinkedList { case empty indirect case node(Int, LinkedList) }
indirect enum SimpleRecursive { case end case next(SimpleRecursive) }
This program defines a recursive enum to represent arithmetic expressions. It builds the expression (5 + 4) * 2 and evaluates it recursively.
import Foundation indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(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) case .multiplication(let left, let right): return evaluate(left) * evaluate(right) } } // Build expression: (5 + 4) * 2 let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let two = ArithmeticExpression.number(2) let product = ArithmeticExpression.multiplication(sum, two) print("Expression evaluates to: \(evaluate(product))")
Time complexity depends on the size of the recursive structure; evaluation visits each node once, so O(n).
Space complexity is O(n) due to the call stack during recursion.
Common mistake: forgetting to mark enum or cases as indirect causes compiler errors.
Use recursive enums when data naturally nests or links to itself; for flat data, simpler types are better.
Recursive enums let you create self-referential data types.
Use indirect to tell Swift about recursion.
Great for trees, linked lists, and nested expressions.