Raw Value Enumerations

If you have used enumerations in a language like C or C++, you may be surprised to learn that Swift enums do not have an underlying integer type. You can, however, choose to get the same behavior by using what Swift refers to as a raw value. To use Int raw values for your text alignment enumeration, change the declaration of the enum.

Listing 14.11  Using raw values

enum TextAlignment: Int {
    case Left
    case Right
    case Center
    case Justify
}
...

Specifying a raw value type for TextAlignment gives a distinct raw value of that type (Int) to each case. The default behavior for integral raw values is that the first case gets raw value 0, the next case gets raw value 1, and so on. Confirm this by printing some ...

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.