DevPrep

All topics › The Swift Language

Which Swift keyword creates recursive enums?

Junior PRO

The idea

indirect. An enum is a value type of fixed size, and a recursive case would contain itself, i.e. have infinite size. indirect tells the compiler to store the payload of such a case on the heap (boxing) and keep only a reference inside the enum. You can mark a single case or the whole enum.

indirect enum Expr {
    case number(Int)
    case add(Expr, Expr)
    case multiply(Expr, Expr)
}

func eval(_ e: Expr) -> Int {
    switch e {
    case .number(let n): n
    case .add(let l, let r): eval(l) + eval(r)
    case .multiply(let l, let r): eval(l) * eval(r)
    }
}

let expr = Expr.add(.number(2), .multiply(.number(3), .number(4)))
print(eval(expr))   // 14

enum Tree<T> {
    case leaf
    indirect case node(Tree, T, Tree)   // indirect on a single case only
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store