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.
Practice
indirect keyword do in a Swift recursive enumeration?Solution
Step 1: Understand the role of
Theindirectindirectkeyword tells Swift that the enum cases can hold references to the enum itself, enabling recursion.Step 2: Identify what recursion means in enums
Recursion means an enum case can contain another instance of the same enum, which requiresindirectto avoid infinite size.Final Answer:
It allows the enum to refer to itself recursively. -> Option AQuick Check:
indirectenables recursion = C [OK]
- Thinking indirect makes enum immutable
- Confusing indirect with class conversion
- Believing indirect disables switch usage
Solution
Step 1: Recall how to declare recursive enums
Swift allows marking the whole enum asindirectto enable recursion for all cases.Step 2: Check each option's syntax
The syntaxindirect enum Tree { case leaf(Int); case node(Tree, Tree) }correctly enables recursion by marking the whole enum indirect. Other options either lack the keyword, apply it only to non-recursive cases (leaving recursive case without), or contain syntax errors such as missing thecasekeyword.Final Answer:
indirect enum Tree { case leaf(Int); case node(Tree, Tree) } -> Option DQuick Check:
Whole enum indirect = A [OK]
- Omitting indirect keyword
- Placing indirect only on some cases incorrectly
- Using indirect outside enum declaration
print(tree.countLeaves())?
indirect enum Tree {
case leaf(Int)
case node(Tree, Tree)
func countLeaves() -> Int {
switch self {
case .leaf(_): return 1
case let .node(left, right):
return left.countLeaves() + right.countLeaves()
}
}
}
let tree = Tree.node(.leaf(1), Tree.node(.leaf(2), .leaf(3)))Solution
Step 1: Understand the tree structure
The tree is: node(leaf(1), node(leaf(2), leaf(3))). It has three leaves: 1, 2, and 3.Step 2: Count leaves recursively
The countLeaves function returns 1 for each leaf and sums counts for nodes. So total leaves = 1 + (1 + 1) = 3.Final Answer:
3 -> Option CQuick Check:
Leaves counted = 3 [OK]
- Counting nodes instead of leaves
- Misunderstanding recursive calls
- Forgetting to sum both sides
enum List {
case end
case node(Int, List)
}Solution
Step 1: Check for recursion support
The enum List has a casenode(Int, List)which refers to itself, so it is recursive.Step 2: Verify use of
Swift requires marking recursive enums or cases withindirectindirect. This enum lacks it, causing a compile error.Final Answer:
Missingindirectkeyword for recursion. -> Option AQuick Check:
Recursive enum needs indirect = B [OK]
- Ignoring indirect keyword requirement
- Thinking recursion needs classes
- Assuming all enum cases need associated values
indirect enum Tree {
case leaf(Int)
case node(Tree, Tree)
func depth() -> Int {
// Your code here
}
}Solution
Step 1: Define depth for leaf nodes
Leaves have depth 0 because they have no children.Step 2: Define depth for node cases
Nodes have depth 1 plus the maximum depth of their two child trees.Final Answer:
Return 0 for leaf, and 1 + max depth of left and right nodes. -> Option BQuick Check:
Depth = 0 for leaf, max + 1 for node = A [OK]
- Using sum instead of max for node depth
- Returning 1 for leaf depth incorrectly
- Using min instead of max for node depth
Ready to prove it?
Pass the test and this pattern moves unknown
