Enumerations in Swift for Newbies.
Enumerations are a way of defining new data types.
In this article I will be talking about the basics of Enumerations, or enum for short
.
Think of an
enum
like a dropdown list, it only consists what’s contained in the dropdown list and you can only choose from that specific list.
Enums are also great for developers as it lowers our chances of errors or typos due to providing us autocomplete.
I think the best way to understand enums
are just by following along and It should hopefully give you an idea of what they are and how there used.
The syntax for enumerations
are structured like so:
Open up playground
to follow along.
Let’s use an example where we would be creating a game and we would be displaying the player’s current level status.
Here’s our enum
:
As you see we called our enum
Levels
then a open brace {
, followed by each case
and closed by }
.
This can also be written all on one line like so:
We can now set a variable to a enumeration case like so:
You can also shorten this as well:
You can do a Switch Statement
for each case.
If your unfamiliar with Switch
cases:
Note:
We don’t declare default
like we usually do in switch cases
.
This is because with enums
, there’s no other possibilities. Only what’s in our enums
needs to be checked for.
If you don’t exhaust all cases then you’ll need to use
default
.
Quick Tip:
Instead of each time inside the switch
to do Levels.One
.
Swift knows we are looking inside the playerLevel
so we can simply use .One
.
So it would instead look like this:
Nice and clean 👍🏼
Raw Values
Instead of having the values set inside the switch statement
, we can actually store them in the enum
with something called Raw Values
.
Let’s create another enum
but this time we are going map them to String
and give each enum
case a value.
In this enum
we have our cases like usual, but this time we have a value for each. In this case we declared it to a String
value.
Let’s choose Apple to set into the variable.
Here is when we can grab it’s rawValue
.
We simply write this:
That’s it!
That’s the basics of Enumerations in Swift.
I hope this helped!
Like always, feel free to leave a comment or suggest any future topics you’d like to see covered.
Thanks for reading!