Bird
Raised Fist0
Swiftprogramming~20 mins

Recursive enumerations in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Recursive Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)
Aempty
Bnode(1, left: node(2, left: empty, right: empty), right: empty)
Cnode(1, left: empty, right: node(2, left: empty, right: empty))
Dnode(2, left: empty, right: empty)
Attempts:
2 left
💡 Hint
Look at how the tree is constructed with left and right children.
🧠 Conceptual
intermediate
1:30remaining
Understanding 'indirect' keyword in recursive enums
Why is the 'indirect' keyword necessary in recursive enumerations in Swift?
AIt makes the enum cases mutable.
BIt enables the enum to be used only with classes.
CIt allows the enum to conform to protocols automatically.
DIt tells Swift to store the enum case indirectly to avoid infinite size during compilation.
Attempts:
2 left
💡 Hint
Think about how recursive data structures are stored in memory.
🔧 Debug
advanced
1: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)
}
ARuntime error: Stack overflow when creating a list.
BCompiler error: Recursive enum 'List' is not marked 'indirect'.
CNo error, code compiles and runs fine.
DCompiler error: Missing associated value label.
Attempts:
2 left
💡 Hint
Check if the enum is marked 'indirect' for recursion.
❓ Predict Output
advanced
2: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())
A12
B9
CCompilation error
D7
Attempts:
2 left
💡 Hint
Evaluate the expression tree from the leaves up.
📝 Syntax
expert
2: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)
}
A
enum Tree {
    case leaf(Int)
    indirect case node(Tree, Tree)
}
B
indirect enum Tree {
    case leaf(Int)
    case node(Tree, Tree)
}
C
enum Tree {
    indirect case leaf(Int)
    case node(Tree, Tree)
}
D
enum Tree {
    case leaf(Int)
    case node(indirect Tree, indirect Tree)
}
Attempts:
2 left
💡 Hint
Only the recursive case needs the 'indirect' keyword before it.

Practice

(1/5)
1. What does the indirect keyword do in a Swift recursive enumeration?
easy
A. It allows the enum to refer to itself recursively.
B. It makes the enum immutable.
C. It converts the enum into a class.
D. It prevents the enum from being used in switch statements.

Solution

  1. Step 1: Understand the role of indirect

    The indirect keyword tells Swift that the enum cases can hold references to the enum itself, enabling recursion.
  2. Step 2: Identify what recursion means in enums

    Recursion means an enum case can contain another instance of the same enum, which requires indirect to avoid infinite size.
  3. Final Answer:

    It allows the enum to refer to itself recursively. -> Option A
  4. Quick Check:

    indirect enables recursion = C [OK]
Hint: Remember: indirect means self-reference allowed [OK]
Common Mistakes:
  • Thinking indirect makes enum immutable
  • Confusing indirect with class conversion
  • Believing indirect disables switch usage
2. Which of the following is the correct syntax to declare a recursive enum case in Swift?
easy
A. enum Tree { case leaf(Int); indirect case node(Tree, Tree) }
B. enum Tree { case leaf(Int); case node(Tree, Tree) }
C. enum Tree { indirect case leaf(Int); case node(Tree, Tree) }
D. indirect enum Tree { case leaf(Int); case node(Tree, Tree) }

Solution

  1. Step 1: Recall how to declare recursive enums

    Swift allows marking the whole enum as indirect to enable recursion for all cases.
  2. Step 2: Check each option's syntax

    The syntax indirect 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 the case keyword.
  3. Final Answer:

    indirect enum Tree { case leaf(Int); case node(Tree, Tree) } -> Option D
  4. Quick Check:

    Whole enum indirect = A [OK]
Hint: Use 'indirect enum' for all recursive cases [OK]
Common Mistakes:
  • Omitting indirect keyword
  • Placing indirect only on some cases incorrectly
  • Using indirect outside enum declaration
3. Given the recursive enum below, what is the output of 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)))
medium
A. 1
B. 2
C. 3
D. 4

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Leaves counted = 3 [OK]
Hint: Count leaf nodes recursively for total leaves [OK]
Common Mistakes:
  • Counting nodes instead of leaves
  • Misunderstanding recursive calls
  • Forgetting to sum both sides
4. Identify the error in this recursive enum declaration:
enum List {
    case end
    case node(Int, List)
}
medium
A. Missing indirect keyword for recursion.
B. Enum cases cannot have associated values.
C. The enum must be a class to be recursive.
D. The case end should have an associated value.

Solution

  1. Step 1: Check for recursion support

    The enum List has a case node(Int, List) which refers to itself, so it is recursive.
  2. Step 2: Verify use of indirect

    Swift requires marking recursive enums or cases with indirect. This enum lacks it, causing a compile error.
  3. Final Answer:

    Missing indirect keyword for recursion. -> Option A
  4. Quick Check:

    Recursive enum needs indirect = B [OK]
Hint: Add indirect to recursive enums or cases [OK]
Common Mistakes:
  • Ignoring indirect keyword requirement
  • Thinking recursion needs classes
  • Assuming all enum cases need associated values
5. How would you modify this recursive enum to safely calculate the depth of a tree, returning 0 for leaves and the maximum depth for nodes?
indirect enum Tree {
    case leaf(Int)
    case node(Tree, Tree)

    func depth() -> Int {
        // Your code here
    }
}
hard
A. Return 1 for leaf, and sum depths of left and right nodes.
B. Return 0 for leaf, and 1 + max depth of left and right nodes.
C. Return 0 for leaf, and sum depths of left and right nodes.
D. Return 1 for leaf, and 1 + min depth of left and right nodes.

Solution

  1. Step 1: Define depth for leaf nodes

    Leaves have depth 0 because they have no children.
  2. Step 2: Define depth for node cases

    Nodes have depth 1 plus the maximum depth of their two child trees.
  3. Final Answer:

    Return 0 for leaf, and 1 + max depth of left and right nodes. -> Option B
  4. Quick Check:

    Depth = 0 for leaf, max + 1 for node = A [OK]
Hint: Depth = 0 leaf, 1 + max child depth node [OK]
Common Mistakes:
  • Using sum instead of max for node depth
  • Returning 1 for leaf depth incorrectly
  • Using min instead of max for node depth
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard