< Why would you want to associate a value with an enum case? | Why can’t Swift add a Double to an Int? > |
Updated for Xcode 14.2
Think about an enum such as this one:
enum Mood {
case happy
case sad
case grumpy
case sleepy
case hungry
}
That lets us use values such as Mood.happy
in our code, which is much safer and more efficient than storing “happy” as a string.
Now think about stuff outside our code – if we were reading the user’s saved data, or downloading something from the internet. Sure, our Swift code knows what Mood.happy
means, but how could we send that value over the internet?
I know this sounds a bit philosophical, but I want you to think about what Mood.happy
really is. How is it stored when our program runs? The point is that we don’t really care most of the time – Swift could internally store it as the number 556, and it wouldn’t make any difference. All we care about is that we get the safety and performance that enums bring.
However, things get more complex when we do need to know how the value is stored. If we need to download a list of users from the internet and know what their current mood is, then that server needs to be able to send that data in a way we can understand.
That’s where enum raw values come in: they let us use enums just like we normally would, but also attach an underlying value to each case. Inside our Swift code this mostly won’t have any effect, but it does mean we now have a specific, fixed way of referring to each value for the times we need it.
So, for our Mood
enum we could ask Swift to provide integer values for each of our cases like this:
enum Mood: Int {
case happy
case sad
case grumpy
case sleepy
case hungry
}
In our code we can carry on writing Mood.happy
, Mood.sad
, and so on, just like before. However, now we can also download some data from a server, and be told “this user has mood 0,” and match that up with Mood.happy
.
If you’re keen to keep learning more about enums, I can recommend Antoine van der Lee’s article on the topic: https://www.avanderlee.com/swift/enumerations/
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.