Normally, enums can't be recursive (because they would require infinite storage):
enum Tree<T> {
case leaf(T)
case branch(Tree<T>, Tree<T>) // error: recursive enum 'Tree<T>' is not marked 'indirect'
}
The indirect
keyword makes the enum store its payload with a layer of indirection, rather than storing it inline. You can use this keyword on a single case:
enum Tree<T> {
case leaf(T)
indirect case branch(Tree<T>, Tree<T>)
}
let tree = Tree.branch(.leaf(1), .branch(.leaf(2), .leaf(3)))
indirect
also works on the whole enum, making any case indirect when necessary:
indirect enum Tree<T> {
case leaf(T)
case branch(Tree<T>, Tree<T>)
}