As well as storing a simple value, enums can also store associated values attached to each case. This lets you attach additional information to your enums so they can represent more nuanced data.
For example, we might define an enum that stores various kinds of activities:
enum Activity {
case bored
case running
case talking
case singing
}
That lets us say that someone is talking, but we don’t know what they are talking about, or we can know that someone is running, but we don’t know where they are running to.
Enum associated values let us add those additional details:
enum Activity {
case bored
case running(destination: String)
case talking(topic: String)
case singing(volume: Int)
}
Now we can be more precise – we can say that someone is talking about football:
let talking = Activity.talking(topic: "football")
SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.