Updated for Xcode 14.2
One of the most powerful features of Swift’s enums is their ability to store one or more associated values – extra pieces of information that describe the enum case in more detail.
Associated values can be attached to every case, or only some cases. Plus, each case can have as many associated values as you want, as long as each one has a type.
For example, we might create a Weather
enum with three cases:
enum Weather {
case sunny
case windy(speed: Int)
case rainy(chance: Int, amount: Int)
}
That means our weather can be sunny, it can be windy, or it can be rainy. However, when it’s windy we’re also asking to store how fast the wind is as an integer – whether it’s 10 kilometers per hour (kph), 20, 30, and so on. And when it’s rainy, we’re storing a percentage chance of the rain happening and a volume value, storing how much rain will store.
We could do something similar, but it would be pretty unpleasant. Imagine this:
enum Weather {
case sunny
case lightBreeze
case aBitWindy
case quiteBlusteryNow
case nowThatsAStrongWind
case thisIsSeriousNow
case itsAHurricane
}
That gives us more ways to describe windy weather, but it’s very imprecise – we’ve gone from being able to distinguish between a 10kph wind and a 15kph wind. Worse, if you hadn’t seen the list ordered like it is above, would you know that aBitWindy
was supposed to be stronger than lightBreeze
but less strong than quiteBlusteryNow
?
Now imagine trying to work with the rainy
case, where we need to store two integers. We’d end up having to have cases that describe a low chance of light rain, a low chance of moderate rain, a low chance of heavy rain, a moderate chance of light rain, a moderate chance of moderate rain… well, you get the point.
So, enums with associated values let us add extra information to an enum case – think of them as being adjectives to a noun, because it lets us describe the thing in more detail.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.