Working with Associated Values in Swift Enums: A Tutorial

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

by The Captain

on
May 12, 2024

Tutorial: Working with Associated Values in Swift Enums

In Swift, enums can have associated values, which allow for storing additional information along with each case of the enum. This feature is useful when you need to associate different types of data with different cases of an enum. Let's explore how to work with associated values in Swift enums.

To define an enum with associated values, you specify the type of data that each case will hold within parentheses. Here's an example of an enum representing different types of shapes with associated values:

enum Shape {
    case rectangle(width: Double, height: Double)
    case circle(radius: Double)
    case square(sideLength: Double)
}

In the above example, the `Shape` enum has three cases, each with associated values specifying the dimensions of the shape. Now, let's see how to create instances of these shapes and access their associated values:

let rect = Shape.rectangle(width: 12.0, height: 8.0)
let circle = Shape.circle(radius: 5.0)
let square = Shape.square(sideLength: 10.0)

switch circle {
case .rectangle(let width, let height):
    print("Rectangle: \(width) x \(height)")
case .circle(let radius):
    print("Circle with radius: \(radius)")
case .square(let sideLength):
    print("Square with side length: \(sideLength)")
}

In the above code snippet, we create instances of the `Shape` enum cases and use a `switch` statement to access their associated values. By pattern matching in the `switch` statement, we can extract the associated values and perform different actions based on the enum case.

Associated values in Swift enums can be used to model a wide range of scenarios, from representing different types of data to encapsulating complex information within enum cases. They provide a powerful way to define structured data types with associated metadata.