DEV Community


Enums & Switch

・1 min read

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.

Discussion (0)