Indirect Enum in swift

Updated 29 November 2021

Save

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

We can also add the associated values with the enum cases as:

But in this blog, I will demonstrate to you what will happen if we try to pass the associated value as enum itself.

And we get the compiler error: Recursive enum ‘Webkul’ is not marked ‘indirect’ and look as:

Without Indirect Enum

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.

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:

Indirect Enum

Indirect compiles the data and store the enum’s data behind a pointerAdd 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.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home