0
0
Swiftprogramming~10 mins

Recursive enumerations in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a recursive enum case.

Swift
enum ArithmeticExpression {
    case number(Int)
    indirect case [1](ArithmeticExpression, ArithmeticExpression)
}
Drag options to blanks, or click blank then click option'
Amultiply
Bdivide
Csubtract
Daddition
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the 'indirect' keyword before the recursive case.
Using a non-arithmetic case name.
2fill in blank
medium

Complete the code to evaluate the recursive enum expression.

Swift
func evaluate(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case .number(let value):
        return value
    case .addition(let left, let right):
        return evaluate(left) [1] evaluate(right)
    }
}
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong arithmetic operator.
Not recursively calling evaluate on both sides.
3fill in blank
hard

Fix the error in the recursive enum declaration by completing the code.

Swift
enum BinaryTree {
    case leaf(Int)
    [1] case node(BinaryTree, BinaryTree)
}
Drag options to blanks, or click blank then click option'
Aindirect
Bfinal
Cstatic
Dlazy
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'indirect' keyword causes a compiler error.
Using unrelated keywords like 'static' or 'lazy'.
4fill in blank
hard

Fill both blanks to create a recursive enum with indirect keyword and a recursive case.

Swift
indirect enum [1] {
    case value(Int)
    case [2]([1], [1])
}
Drag options to blanks, or click blank then click option'
AExpression
BTree
CNode
DBinaryTree
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name for enum and case.
Not matching the recursive case parameter types to the enum name.
5fill in blank
hard

Fill all three blanks to complete the recursive enum and a function that counts nodes.

Swift
indirect enum [1] {
    case leaf(Int)
    case branch([1], [1])
}

func countNodes(_ tree: [1]) -> Int {
    switch tree {
    case .leaf(_):
        return 1
    case .branch(let left, let right):
        return countNodes(left) [2] countNodes(right) + 1
    }
}
Drag options to blanks, or click blank then click option'
ATree
B+
CTreeNode
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using different enum names in function parameters.
Using subtraction instead of addition when counting nodes.