What is indirect enum in swift?
--
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.
Alternatively, we can also specify associated values of any type with the enum cases:
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.
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.
Alternatively, we can write indirect
keyword before the enum
keyword to enable indirection for all the cases that have an associated value.
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 caseindirect 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! 👨🏼💻