DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
keepoSteepo
keepoSteepo

Posted on

Enums & Switch

When building an app, one might consider using an enum/ enumeration instead of a String or Int to limit the choices a user can pick from. Expecting the user to input their choice via String or Int opens the door to millions of possibilities. Instead, create a new type with an enum where instances of that type can only have values correlating to one of the specified cases. Each possible value in an enum is called case. When using enums, it’s always clear what the possible values are and what they mean. Enum values can be compared using ==, or a switch statement to test for all possible values.

A switch statement is another way of making decisions in your code. They can be used to switch any type of value but work especially well with enums. One thing to note about switch statements is that they must be exhaustive, meaning every possible case in the enum must be dealt with. To handle an unspecified value, use a default case.
Finally, like structs, you can add calculated properties and methods to enums.

Top comments (0)

Yes, this is technically an β€œad”, but hear me out.

We have 900k+ developers reading, posting, and enjoying community, and would love to have you.

Create an account and continue your coding journey.