Associated Values in Swift: Enhancing Enumerations with Extra Data

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 6, 2024
Working with Associated Values in Swift

Working with Associated Values in Swift

Associated values in Swift allow you to attach additional data to an enumeration case. This can be useful when you need to store extra information along with a particular case in an enumeration. Let's take a look at how you can work with associated values in Swift:

enum Product {
    case electronic(name: String, price: Double)
    case book(title: String, author: String)
}

let laptop = Product.electronic(name: "Macbook Pro", price: 1999.99)
let book = Product.book(title: "The Alchemist", author: "Paulo Coelho")

func printProductDetails(product: Product) {
    switch product {
    case .electronic(let name, let price):
        print("Electronic: \(name), Price: $\(price)")
    case .book(let title, let author):
        print("Book: \(title) by \(author)")
    }
}

printProductDetails(product: laptop)
printProductDetails(product: book)}

In the code snippet above, we have defined an enumeration called `Product` with two cases: `electronic` and `book`. The `electronic` case has associated values `name` and `price`, while the `book` case has associated values `title` and `author`.

We then create instances of `Product` with different associated values and use a `printProductDetails` function to print out the details of each product. The associated values allow us to access and use the additional data stored within each case.

Working with associated values in Swift can be very powerful and flexible, allowing you to create complex data structures with ease. It is a great feature to use when you need to represent different types of data within a single enumeration.