Enumerations

So far, we have covered two of the three types of classification in Swift: structure and class. The third classification is called enumeration. Enumerations are used to define a group of related values for an instance. For example, if we want values to represent one of the three primary colors, an enumeration is a great tool.

Basic declaration

An enumeration is made up of cases much like a switch and uses the keyword enum instead of struct or class. An enumeration for primary colors should look like this:

enum PrimaryColor {
    case Red
    case Green
    case Blue
}

You can then define a variable with this type and assign it one of the cases:

var color = PrimaryColor.Green

Note that, to use one of the values, we must use the name of the type followed ...

Get Swift: Developing iOS Applications 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.