Enum is a Swift common data type. It helps us to group some related values. For creating a Swift Enum you just need an ENUM keyword.
For example, in some programs, we need to give users select their gender before registration. Let’s create a HumanV1 struct for these goals:
So our HumanV1 has 2 properties title: String and gender: String. How can we check if the current human is male? We have only one way to do that:
And this way is disgusting because we always need to type this word male and if we will need to rename it to man for example, that we will need to do that on the whole project. The Second problem is to remember all these types of property. We need to tell to all developers on this project that property of gender can be only “male” or “female” Strings without uppercases and etc. So let’s check how Enums can solve these problems.
In HumanV2 gender, the property has a Gender type and we can see that we can simply set one of these cases on creating Alex and Mia constants. (We can just use shorthand like “.female” without full type name Gender because struct know what the type of his gender constant). After that, we can simply check if Mia is a female. Xcode IDE knows Gender Enum and its cases, that's why it is so easy to check variables on Gender cases. If some variable in another place will have Gender type it will prevent setting to this variable some wrong value like man or woman. It will never happen because they aren’t Gender cases and all developers on this project will have only male or female cases for use.
How to get a list of all cases in Enum?
If we need an ability to get a list of all existing cases inside Enum, we just need to conform CaseIterable protocol to our Enum. And it will get an allCases property which will return all the cases in this Enum
How to get a String RawValue for each case on Enum?
If we need not just to use these cases for checking the gender, but and for showing the value of these cases to the user (in a dropdown for example) then we need to inherit a String. And it will give us a string value of each case.
So the rawValue of the female is FEMALE String and male is a male String (because it wasn’t redefined). Now we can simply show to users this rawValue because this is a string. Actually we can inherit any type like Int or Double for example. And the rawValues will be an Int and Double accordingly.
I hope you enjoyed this post. If you like it, don’t forget to share it with your friends and coworkers so they can know more about Enums and their usage.