Why does Swift reject a recursive enum for an expression tree with "recursive enum 'Expr' is not marked 'indirect'", and what does `indirect` change?
answer
- value types need a fixed size
- a case that contains itself
- payload moved into a heap box
- per case or whole enum
- Array already adds the indirection
basics
~20 sAn enum is a value type with a fixed size, and a case that stores another Expr inline would make that size infinite. indirect makes the compiler store that case's payload in a separately allocated box and keep only a reference inline.
solid answer
~40 sSwift lays an enum out inline, big enough for its largest payload plus a tag, so `case add(Expr, Expr)` would need an `Expr` inside an `Expr` without end, and the compiler refuses with "recursive enum 'Expr' is not marked 'indirect'". Writing `indirect case add(Expr, Expr)`, or `indirect enum Expr` for every payload case, tells the compiler to insert a layer of indirection: the payload lives in a heap-allocated, reference-counted box. The enum keeps value semantics, because you change an enum value by assigning a new case, never by editing a shared box. The cost is an allocation each time an indirect case is created plus reference counting on copies. Recursion through `Array` or `Dictionary` needs no `indirect`, since those already store elements in a heap buffer; recursion through `Optional` or a tuple still does.
code
swift · 24 linesindirect enum Expr {
case number(Int)
case add(Expr, Expr)
case multiply(Expr, Expr)
var value: Int {
switch self {
case .number(let n): return n
case let .add(lhs, rhs): return lhs.value + rhs.value
case let .multiply(lhs, rhs): return lhs.value * rhs.value
}
}
}
// (5 + 4) * 2
let expr = Expr.multiply(.add(.number(5), .number(4)), .number(2))
print(expr.value) // 18
// No indirect needed: Array keeps its elements in its own heap buffer.
enum MenuItem {
case action(String)
case submenu(String, [MenuItem])
}
let menu = MenuItem.submenu("File", [.action("Open"), .action("Save")])go deeper
Recall that a recursive enum such as an expression tree needs the indirect keyword before the compiler accepts it.
Explain the fixed-size layout of value types, why a self-containing case has no finite size, and how indirect moves the payload into a box.
Choose between case-level and enum-level indirect for allocation cost, and explain why Array-based recursion compiles while Optional-based recursion does not.
Weigh an indirect enum tree against a class-based tree for large or shared structures: value semantics and exhaustive matching versus identity, in-place mutation and allocation counts.
## Why the compiler refuses Structures and enumerations are **value types**: a value is stored inline, in a variable, a parameter or another value's storage, and its size is known at compile time. For an enum, that size is roughly the largest payload plus a tag that says which case is active. Now consider an arithmetic expression tree: - `case number(Int)` needs room for an `Int`; - `case add(Expr, Expr)` needs room for two whole `Expr` values, each of which may itself be an `add` holding two more. No finite size satisfies that definition, so the compiler stops with "recursive enum 'Expr' is not marked 'indirect'". The Swift book's reference manual states the reason directly: enumerations have value semantics and a fixed layout in memory, so to support recursion the compiler must insert a layer of indirection. ## What `indirect` does The `indirect` modifier asks for that indirection explicitly: - on a single case, `indirect case add(Expr, Expr)`, only that case's payload is moved out of line; - on the whole enum, `indirect enum Expr`, every case that has an associated value is moved out of line, including `number(Int)`; - the payload is stored in a **heap-allocated, reference-counted box**, and the enum value holds a reference to it; on a 64-bit platform `MemoryLayout<Expr>.size` is 8 for a fully indirect `Expr`; - cases without payloads are unaffected, and an `indirect` case **must** have an associated value, or the compiler reports "enum case 'empty' without associated value cannot be 'indirect'"; - a case inside an `indirect enum` cannot repeat the modifier: "enum case in 'indirect' enum cannot also be 'indirect'". ## Value semantics survive Copying an indirect enum value copies the reference to the box, so two copies can share one box. That is safe because Swift has no way to edit an enum payload in place: to change a value you assign a new case, for example `expr = .add(expr, .number(1))`, which creates a new box and leaves every other copy untouched. From the outside, an indirect enum behaves exactly like any other value type, with no identity and no `===`. ## Building and reading a tree Construction looks like nested function calls: `Expr.multiply(.add(.number(5), .number(4)), .number(2))` is the tree for `(5 + 4) * 2`. Code that reads it is naturally recursive, for example a computed property `value` that returns the number for `.number` and combines `lhs.value` and `rhs.value` for the operators, giving 18 here. Two consequences follow: - each indirect node built is one heap allocation, so a parser that builds a large tree allocates in proportion to its node count; - recursive evaluation uses call-stack depth in proportion to the tree's depth, which matters only for very deep, unbalanced trees. ## When you do not need it The compiler only demands `indirect` when the enum would contain itself **inline**. Compare: | Payload | Needs `indirect`? | Why | |---|---|---| | `case add(Expr, Expr)` | yes | `Expr` stored directly | | `case next(Node?)` | yes | `Optional` stores its wrapped value inline | | `case wrapped((Node, Int))` | yes | a tuple stores its elements inline | | `case children([Node])` | no | `Array` keeps elements in its own heap buffer | So a menu tree written as `case submenu(String, [MenuItem])` compiles as is. ## Choosing case-level or enum-level 1. Mark **only the recursive cases** when the leaf cases are hot and small: `number(Int)` then stays inline with no allocation, and the enum is 9 bytes on a 64-bit platform instead of 8 plus a box per number. 2. Mark the **whole enum** when most cases are recursive and readability matters more; one keyword covers every payload case. 3. Remember the box is not free: building a large tree allocates once per indirect node, and an indirect enum cannot conform to `BitwiseCopyable` ("indirect enum cannot conform to 'BitwiseCopyable'"). ## What interviewers listen for A strong answer explains the fixed-size layout that makes self-containment impossible, says `indirect` boxes the payload on the heap while the enum keeps value semantics, and knows that `Array` already supplies indirection while `Optional` does not. Evaluating the tree means matching each case, which the lesson on case patterns covers.
- Does `indirect` turn the enum into a reference type?No. Copies may share one box, but Swift offers no way to edit a payload in place: changing the value means assigning a new case, which allocates a new box. There is no identity to compare with `===`, and the type still behaves as a value type in every observable way.
- Why does `case next(Node?)` still need `indirect` when `case children([Node])` does not?`Optional` is itself an enum that stores its wrapped value inline, so `Node?` contains a whole `Node` and the size is still infinite. `Array` stores only a reference to a heap buffer inline, so its size does not depend on `Node`, and the compiler accepts the recursion.
- `indirect` makes the enum a reference type with shared mutable state.
- Every recursive enum needs `indirect`, even when it recurses through an `Array`.
- `indirect` is an optimization hint the compiler is free to ignore.
- Marking an enum `indirect` boxes its cases without associated values too.
- Wrapping the recursive payload in an Optional removes the need for `indirect`.