Before knowing the indirect enum, I will give an overview of the enum. An enum defines the same or common type for a group of related values and provides features to work with those related values in a type-safe manner in developing the module.
Syntax
1 2 3 4 5 |
enum YourEnum { // enum definition written here case Webkul case Mobikul } |
We can also add the associated values with the enum cases as:
1 2 |
case Webkul(String, Int) case Mobikul(String) |
But in this blog, I will demonstrate to you what will happen if we try to pass the associated value as enum itself.
1 2 3 4 5 |
enum Webkul { case Mobikul(Webkul) case Cloudkul } |
And we get the compiler error: Recursive enum ‘Webkul’ is not marked ‘indirect’ and look as:
Enums are value types, due to this Apple memory management works on compile-time. And we have an idea that how many memory counts we need to allocate for each instance.
When we add the one value type object inside the same value type object then we create a recursion. In case of this recursion, it is not possible that how much memory can be required for that object. So we need to know how can we deal with this situation.
Apple in swift introduces the indirect enumerations which tell the compiler to insert the necessary layer of indirection.
1 2 3 4 |
enum Webkul{ indirect case Mobikul(Webkul) case Cloudkul } |
You can also write indirect before the beginning of the enumeration to enable indirection for all of the enumeration’s cases that have an associated value:
1 2 3 4 5 |
indirect enum Webkul{ case Bagisto case Mobikul(Webkul) case Cloudkul(Webkul) } |
Indirect compiles the data and store the enum’s data behind a pointer. Add another layer of static memory size is allocated for storing the data. Thus after these optimizations, no need to make the instance of Enum big enough to hold the whole data.
Conclusion
I hope this blog will help you in the understanding of recursive enumerations if still you have any comments, questions, or recommendations, feel free to post them in the comment section below!
For other blogs, please click here.