What is indirect enum in swift?

Milan Panchal
Geek Culture
Published in
3 min readDec 13, 2021

--

In this article, we’ll learn what is indirect or recursive enumeration. But let’s first understand enumeration in swift.

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

enumeration in Swift

Alternatively, we can also specify associated values of any type with the enum cases:

enumeration with associated values in swift

Now let’s understand what is indirect or recursive enumeration?

When we add the one value type object inside the same value type object then we create a recursion.

enumeration with recursion in swift

As we know, Swift enums are value types and the size of the type should be calculated at compile time. But it is not possible to calculate the final size of the recursive enum.

To overcome the situation, we indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to store the associated enum indirectly (i.e. by reference) instead of value.

We called them indirect enum because they modify the way swift stores them.

Example: indirect enum case in swift

Alternatively, we can write indirect keyword before the enum keyword to enable indirection for all the cases that have an associated value.

Example: indirect enum in swift

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

Conclusion

  • Swift enums are value types and the size of the type should be calculated at compile time.
  • An indirect enum is an enum that references oneself as the associated value.
  • indirect keyword tells the compiler to insert the necessary layer of indirection.
  • indirect case will stored as reference type only for that case
  • indirect enum will stored as reference for all the assocaited cases

Questions?

Please feel free to comment below, if you have any questions.

If you like this article, feel free to share it with your friends and leave me a comment. Also, click on the clap button (👏) below to show how much you like the article.

Thanks for reading! 👨🏼‍💻

--

--

Milan Panchal
Geek Culture

iOS Team Lead ǁ Swift ǁ Objective-C ǁ Lifelong Learner ǁ Blogger — Join Medium from the following link: https://medium.com/@milanpanchal24/membership