Challenge - 5 Problems
Recursive Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple recursive enum with indirect case
What is the output of this Swift code when printed?
Swift
enum BinaryTree { case empty indirect case node(Int, left: BinaryTree, right: BinaryTree) } let tree = BinaryTree.node(1, left: .empty, right: .node(2, left: .empty, right: .empty)) print(tree)
Attempts:
2 left
💡 Hint
Look at how the tree is constructed with left and right children.
✗ Incorrect
The tree has root node 1 with left child empty and right child node 2 with empty children. Printing the enum shows the structure with cases and associated values.
🧠 Conceptual
intermediate1:30remaining
Understanding 'indirect' keyword in recursive enums
Why is the 'indirect' keyword necessary in recursive enumerations in Swift?
Attempts:
2 left
💡 Hint
Think about how recursive data structures are stored in memory.
✗ Incorrect
Recursive enums can have infinite size if stored directly. The 'indirect' keyword tells Swift to store the case by reference, preventing infinite size and enabling recursion.
🔧 Debug
advanced1:30remaining
Identify the error in this recursive enum definition
What error will this Swift code produce?
Swift
enum List { case empty case node(Int, List) }
Attempts:
2 left
💡 Hint
Check if the enum is marked 'indirect' for recursion.
✗ Incorrect
Recursive enums must be marked 'indirect' to compile because the compiler needs to know to store the recursive case indirectly to avoid infinite size.
❓ Predict Output
advanced2:00remaining
Output of recursive enum with computed property
What is the output of this Swift code?
Swift
indirect enum Expression { case number(Int) case addition(Expression, Expression) func evaluate() -> Int { switch self { case .number(let value): return value case .addition(let left, let right): return left.evaluate() + right.evaluate() } } } let expr = Expression.addition(.number(3), .addition(.number(4), .number(5))) print(expr.evaluate())
Attempts:
2 left
💡 Hint
Evaluate the expression tree from the leaves up.
✗ Incorrect
The expression represents 3 + (4 + 5). Evaluating recursively sums 3 + 9 = 12.
📝 Syntax
expert2:00remaining
Correct syntax for marking only one case as indirect
Which option correctly marks only the recursive case as indirect in this enum?
Swift
enum Tree { case leaf(Int) case node(Tree, Tree) }
Attempts:
2 left
💡 Hint
Only the recursive case needs the 'indirect' keyword before it.
✗ Incorrect
Option A correctly marks only the 'node' case as indirect. Option A marks the whole enum indirect, which is valid but not what the question asks. Option A incorrectly marks the non-recursive case. Option A uses invalid syntax.