Enumerations and the Switch Statement

An enumeration is a type with a discrete set of values. Define an enum describing pies:

enum PieType {
    case apple
    case cherry
    case pecan
}

let favoritePie = PieType.apple                              apple

Swift has a powerful switch statement that, among other things, is great for matching on enum values:

let name: String
switch favoritePie {
case .apple:
    name = "Apple"                                           "Apple"
case .cherry:
    name = "Cherry"
case .pecan:
    name = "Pecan"
}

The cases for a switch statement must be exhaustive: Each possible value of the switch expression must be accounted for, whether explicitly or via a default case. Unlike in C, Swift switch cases do not fall through – only the code for the case that is matched is executed. (If you need the fall-through behavior of C, you can explicitly request it using the fallthrough keyword.)

Switch statements can match on many types, including ranges:

    let macOSVersion: Int = ...
    switch macOSVersion {
    case 0...8:
        print("A big cat")
    case 9...15:
        print("California locations")
    default:
        print("Greetings, people of the future! What's new in 10.(macOSVersion)?")
    }

For more on the switch statement and its pattern matching capabilities, see the Control Flow section in Apple’s The Swift Programming Language guide. (More on that in just a moment.)

Enumerations and raw values

Swift enums can have raw values associated with their cases. Add this to your PieType enum:

enum PieType: Int {
    case apple = 0
    case cherry
    case pecan
}

With the type specified, you can ask an instance of PieType for its rawValue and then initialize the enum type with that value. This returns an optional, since the raw value may not correspond with an actual case of the enum, so it is a great candidate for optional binding.

let pieRawValue = PieType.pecan.rawValue                2

if let pieType = PieType(rawValue: pieRawValue) {
    // Got a valid 'pieType'!
    print(pieType)                                      "pecan
"
}

The raw value for an enum is often an Int, but it can be any integer or floating-point number type as well as the String and Character types.

When the raw value is an integer type, the values automatically increment if no explicit value is given. For PieType, only the apple case is given an explicit value. The values for cherry and pecan are automatically assigned a rawValue of 1 and 2, respectively.

There is more to enumerations. Each case of an enumeration can have associated values. You will learn more about associated values in Chapter 20.

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

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