Associated values

Enumerations can store associated values of any given type, and the value types can be different for each member of the enumeration if required. Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages. The following example presents a simple usage of associated values:

enum Length {
    case us(Double)
    case metric(Double)
}

let lengthMetric = Length.metric(1.6)

The enumeration type, Length, can either take a value of US with an associated value of the Double type or a value of metric with an associated value of the Double type.

The lengthMetric is a variable that gets assigned as a value of Length.metric with an associated value of 1.6.

As seen in the preceding example, associated values are set when we create a new constant or variable based on one of the enumeration's cases and can be different each time we do so.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset