Understanding Indirect Enums in Swift

Recursive types

Steven Curtis
5 min readAug 12, 2024
Photo by Armand Khoury on Unsplash

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?

--

--