Swift Enum With Labeled Associated Values

Swift Enum With Labeled Associated Values

Clarity is more important than brevity

Β·

2 min read

In this blog post, I talk about a feature in the Swift Programming Language that may not be obvious for developers working with enumerations. This feature helps to provide clarity about enum cases with associated values.

The Swift Programming Language Guide provides the following example for declaring an enumeration to store values of other types alongside these case values.

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

You can then create new barcodes of type .upc and use them as follows:

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
    print("QR code: \(productCode).")
}

I find it interesting that the developer, who wrote the switch statement has a deep insight into what those four associated Int values represent. The meaning of the associated values was neither communicated through markup documentation nor was it part of the enum declaration.

There is another way that is not covered by the respective section of the Swift Programming Language Guide: you can add labels for the associated values when declaring the enum case!

All the credits go to Labelling Associated Values? Swift forums post to discuss this option.

Let's re-write the enum case statement for upc:

enum Barcode {
    case upc(numberSystem: Int, manufacturer: Int, product: Int, check: Int)
    case qrCode(String)
}

This will change how people initialize the productBarcode variable.

var productBarcode = Barcode.upc(numberSystem: 8, manufacturer: 85909, product: 51226, check: 3)

Adding or not adding labels to enum cases does not impact the switch statement on our variable holding the enum case.

For the given example, I like the use of labels. It reminds me of the fundamentals explained in the Swift API Design Guidelines:

Clarity is more important than brevity

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!