0
0
Swiftprogramming~5 mins

Associated values per case in Swift

Choose your learning style9 modes available
Introduction

Associated values let you store extra information with each option in an enum. This helps keep related data together in a simple way.

When you want to group different types of related data under one category.
When you need to store extra details for each choice in a list of options.
When modeling real-world things that have different properties depending on their type.
When you want to keep code organized by combining data and options in one place.
Syntax
Swift
enum EnumName {
    case optionName(AssociatedType)
    case anotherOption(AssociatedType1, AssociatedType2)
}

Each case can have zero or more associated values inside parentheses.

Associated values can be of any type, including multiple values separated by commas.

Examples
This enum has cases with different associated values and one without any.
Swift
enum Vehicle {
    case car(make: String, year: Int)
    case bicycle(brand: String)
    case truck
}
Each case stores extra information about success or failure.
Swift
enum Result {
    case success(data: String)
    case failure(errorCode: Int)
}
Sample Program

This program defines a Beverage enum with associated values. It creates a coffee with size and sugar info, then prints those details using a switch.

Swift
enum Beverage {
    case coffee(size: String, sugar: Bool)
    case tea(flavor: String)
    case water
}

let myDrink = Beverage.coffee(size: "Large", sugar: true)

switch myDrink {
case .coffee(let size, let sugar):
    print("Coffee size: \(size), sugar added: \(sugar)")
case .tea(let flavor):
    print("Tea flavor: \(flavor)")
case .water:
    print("Just water")
}
OutputSuccess
Important Notes

You access associated values by matching them in a switch or using if case let.

Associated values are different from raw values; they store data per instance, not fixed constants.

Summary

Associated values let enum cases carry extra data.

They help model complex data clearly and safely.

Use switch statements to extract and use associated values.