Search code examples
swiftenumslanguage-lawyerumlclass-diagram

Swift's enum with associated values in an UML class diagram


This is an UML question related to Swift. It is not a Swift programming question

Swift provides an enum type that can be exactly like enumerations in UML: It has a value semantic, defines a set of literals, and may have operations. The only difference is that it cannot have attributes (not even constant ones like in Java).

But Swift provides also enums with associated values. Example:

enum Beverage {
    case water
    case juice(String)
    case tea(flavor: String)
    case coffee (strength: Int)
    case other
}  

let b1 = Beverage.water
let b2 = Beverage.juice("Apple")
let b3 = Beverage.tea(flavor: "mint")
let b4 : Beverage = .coffee(strength: 3)

The associated values are provided at initialization of an instance, and are not directly accessible and can only be retrieved using pattern matching, i.e. in a switch statement, instead of

case .tea:

we could use:

case let .tea(taste):    // if the case branch is fired, taste contains the value

It would be tempting to use a simple enumeration and ignore the the associated values:

enter image description here

However, this does not capture the real nature of the swift enum, considering the UML specs:

An EnumerationLiteral defines an element of the run-time extension of an Enumeration. Values corresponding to EnumerationLiterals are immutable and may be compared for equality. EnumerationLiterals may not change during their existence, so any attributes on an Enumeration shall be read-only.

The last sentence corresponds to the situation of a Java enum where you can associate a set of constant attributes to specific enumeration literals. It's not fully applicable to swift's associated values, where the associated values can change depending on the literal, and moreover the same literal may be associated to different values.

How to best model this kind of enum in UML?


Solution

  • I would model this as a set of datatypes specializing Beverage:

    enter image description here

    Swift might add some syntactic sugar, but essentially this is what it comes up to. At least as far as my limited understanding of swift enumerations goes.