Harnessing Associated Values in Swift Enumerations

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

by The Captain

April 5, 2024

Working with Associated Values in Swift Enumerations

Swift Enumerations are a powerful feature that allows you to define a common type for a group of related values. One interesting aspect of Enumerations in Swift is the ability to associate additional values with each case, known as Associated Values.

Defining an Enumeration with Associated Values

Associated Values allow you to attach extra information to the cases of an Enumeration. This can be useful when you need to store different types of data for each case. Here's an example of defining an Enumeration with Associated Values:

enum Measurement {
    case distance(Double)
    case time(Int)
    case temperature(Double)
In this example, the `Measurement` Enumeration has three cases: `distance`, `time`, and `temperature`, each with an associated value of a different type.

Using Enumerations with Associated Values

Once you have defined an Enumeration with Associated Values, you can use pattern matching to extract and work with the associated values. Here's an example of how you can use the `Measurement` Enumeration:

func displayMeasurement(_ measurement: Measurement) {
    switch measurement {
    case .distance(let value):
        print("Distance: \(value) meters")
    case .time(let value):
        print("Time: \(value) seconds")
    case .temperature(let value):
        print("Temperature: \(value) degrees Celsius")

let distance = Measurement.distance(10.5)

let time = Measurement.time(30)

let temperature = Measurement.temperature(25.0)
In this code snippet, we define a function `displayMeasurement` that takes a `Measurement` value and prints out the associated value based on the case. We then create instances of the `Measurement` Enumeration with different associated values and call the `displayMeasurement` function to display the information.


Associated Values in Swift Enumerations provide a flexible way to work with different types of data within a single Enumeration type. By associating values with Enumeration cases, you can create more expressive and versatile data types in your Swift code.