Recursive Enum in Swift

Level 5468 keystrokes

Expression is an indirect enum whose cases can contain other Expressions, so it can represent a tree such as (2 × 3) + 4. evaluate walks the tree recursively and prints Result: 10.

Swift code

// indirect stores associated values by reference, so cases can contain Expression
1indirect enum Expression {
// Leaf: a plain number
2 case number(Int)
// Nodes that combine two sub-expressions
3 case add(Expression, Expression)
4 case multiply(Expression, Expression)
5}
6
7func evaluate(_ expr: Expression) -> Int {
8 switch expr {
// Base case: a number evaluates to itself
9 case .number(let n):
10 return n
// Recursive cases: evaluate both sides, then combine
11 case .add(let left, let right):
12 return evaluate(left) + evaluate(right)
13 case .multiply(let left, let right):
14 return evaluate(left) * evaluate(right)
15 }
16}
17
// Builds the tree for (2 × 3) + 4
18let expr = Expression.add(
19 .multiply(.number(2), .number(3)),
20 .number(4)
21)
// 6 + 4: prints Result: 10
22print("Result: \(evaluate(expr))")

Output

Result: 10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 19
  • )× 19
  • .× 8
  • ,× 6
  • :× 5
  • {× 3
  • }× 3
  • "× 2
  • _× 1
  • -× 1

More Swift examples at level 5

← Swift typing practice