Member-only story
Understanding Indirect Enums in Swift
Recursive types
Enums in Swift provide access to related groups of values in a type-safe manner, and use value semantics. While in some sense they are similar to the use of struct, they embody their own complexity.
This article is about the use of the `indirect` keyword that allows recursively defined cases, something disallowed in Swift for structs.
I want to explain what indirect enums are and how to implement them.
Terminology
enum: A user-defined type in Swift that groups related values in a type-safe way.
indirect: A keyword in Swift used to indicate that an enum case (or all enum cases when applied to an enum) enabling recursive data structures.
struct: A value type in Swift that encapsulates related data and behaviours, and uses value semantics.
class: A reference type in Swift that encapsulates related properties and methods. Supports inheritance and dynamic dispatch.
type-safety: A feature of Swift that ensures variables are used in a way consistent with their declared types, preventing compile time errors.
What are Indirect Enums?
Indirect enums are useful because we can define recursive data structures.
This means that an enum case can refer to another instance of the same enum.
This is all a little abstract, so let us see when you might use a recursive data structure.
Uses of Indirect Enums
Classic uses of indirect enums are
Binary Tree structures
Each Node has child nodes (in a binary tree left and right nodes). If we wish to use value semantics while using an enum we can use an indirect enum.
indirect enum Node<T> {
case node(
value: T,
leftChild: Node?,
rightChild: Node?
)
case empty
}
Linked List
Each Node in a linked list points to the next element, again providing a recursive data structure.
indirect enum Node<T> {
case…