Associated Values

Everything you have done so far with enumerations falls into the same general category of defining static cases that enumerate possible values or states. Swift also offers a much more powerful flavor of enumeration: cases with associated values. Associated values allow you to attach data to instances of an enumeration, and different cases can have different types of associated values.

Create an enumeration that allows for tracking the dimensions of a couple of basic shapes. Each kind of shape has different types of properties. To represent a square, you need a single value (the length of one side). To represent a rectangle, you need two values: a width and a height.

Listing 14.24 Setting up ShapeDimensions

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.