What are some examples where enumerations with indirection are preferred to a class?

The Swift Programming Language shows a brief example of a recursive tree structure

enum Tree<T> {
    case empty
    indirect case node(value: T, left: Tree, right: Tree)
}

When and why might it be a better fit to structure data as an enum with indirection instead of a class, and vice-versa?

2 Likes
  1. Classes are reference types, enums are value types. They behave very differently when you copy and then modify them.

  2. You cannot use just a class, if you want to have recursion you need an enum + a class. The Tree example was so similar to Optional that I used it (Optional is an enum with two cases, one empty and one with stuff, similar to the Tree) but there are more complex situations where you would have to define two types instead of one

I did a quick & small project to compare:

Found out that (with large data sets) enum is significantly slower due to being value type, compared to classes.

Please let me know if you find places for improvements.