Kelvin Lau Kelvin Lau - 1 year ago 90
Swift Question

indirect enums and structs

To start off, I want to say that I'm aware there are many articles and questions within SO that refer to the

keyword in Swift.

The most popular explanation for the usage of
is to allow for recursive structs and enums.

Rather than just knowing about what
allows us to do, I would like to know how it allows us to use recursive structs and enums.


Is it because structs and enums are value types and value types do not scale well if they are built in a recursive structure? Why?

modify the value type behaviour to behave more like a reference type?

The following two examples compile just fine. What is the difference?

indirect enum BinaryTree<T> {
case node(BinaryTree<T>, T, BinaryTree<T>)
case empty

enum BinaryTree<T> {
indirect case node(BinaryTree<T>, T, BinaryTree<T>)
case empty

Answer Source

The indirect keyword introduces reference semantics.

You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection.

From here

The important part of structs and enums is that they're a constant size. Allowing recursive structs or enums directly would violate this, as there would be an indeterminable number of recursions, hence making the size non constant and unpredictable. indirect uses a constant size reference to refer to a constant size struct.

There's a different between the two code snippets you show.

  1. The first piece of code makes BinaryTree<T> stored by a reference everywhere it's used.

  2. The second piece of code makes BinaryTree<T> stored by a reference only in the case of node. I.e. BinaryTree<T> generally has regular value semantics, except for this explicitly indirect node case.