Labelling Associated Values?

I saw a code example on the web that labels the types of associated values in an enum declaration, and I immediately thought it wouldn't compile because this feature isn't mentioned in the Swift 5.1 guide. But it does compile! For example:

case failure(code: Int, error: Error)

I did find a discussion about [SE-0155][Discuss] the role of labels in enum case patterns, but didn't read the entire thread.

So what's going on? We should steer clear of labelling associated types? Why does the code compile, and does anyone know what the future might hold for this feature?

You're right, it's strange that this doesn't seem to be mentioned in the enumeration section of the documentation, perhaps you could file a bug about that. You can label associated values to document them, and you definitely should in any cases where it isn't obvious from the case name and/or types. For example, this enum from the language guide:

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

would probably be better written as

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

or similar, so it isn't just a soup of integers.

1 Like

So far as I know this feature works because the associated data of an enumeration case is essentially a tuple with some destructuring sugar on top. This harkens back to the older days of Swift when many things were basically tuples and had tuple-like syntax.

In this context, I think there is no reason to either mandate or avoid labelling the tuple elements. It is a tool that can be used in cases where you’d like the extra clarity, and that can be avoided when doing so makes no sense. SwiftNIO does both, depending on the situation.

1 Like

As has been mentioned up thread using labels can help the code be more readable. I also wouldn't worry about this feature getting removed as it would be a rather large source breaking change at this point. IIRC this behaviour has been around since Swift 1.0.

1 Like

Thanks for the advice.

Seems like a reasonable thing to add. Looks like there's an existing example that coincidentally includes that in the reference: https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID537

1 Like
Terms of Service

Privacy Policy

Cookie Policy