What if you could keep all related data together and never lose track of it again?
Why Associated values per case in Swift? - Purpose & Use Cases
Imagine you have different types of messages in an app: text messages, images, and locations. You try to handle each type separately by creating many variables and functions for each detail.
This manual way quickly becomes messy and confusing. You have to remember which variable belongs to which message type, and adding new message types means changing lots of code. It's easy to make mistakes and hard to keep track.
Using associated values per case lets you group each message type with its own related data in one place. This keeps your code clean and organized, making it easy to add new types without breaking existing code.
enum MessageType {
case text
case image
case location
}
var textContent: String?
var imageURL: String?
var locationCoords: (Double, Double)?enum Message {
case text(String)
case image(String)
case location(Double, Double)
}This concept lets you elegantly handle different data types together, making your code simpler, safer, and easier to extend.
In a chat app, you can represent each message with its own data--text, image URL, or GPS coordinates--without juggling many separate variables.
Manual handling of related data is error-prone and hard to maintain.
Associated values group data with each case neatly and safely.
This makes your code cleaner and easier to expand.