Enumerations and Associated Values

You learned about the basics of enumerations in Chapter 2, and you have been using them throughout this book – including in this chapter. Associated values are a useful feature of enumerations. Let’s take a moment to look at a simple example before you use this feature in Photorama.

Enumerations are a convenient way of defining and restricting the possible values for a variable. For example, let’s say you are working on a home automation app. You could define an enumeration to specify the oven state, like this:

    enum OvenState {
        case on
        case off
    }

If the oven is on, you also need to know what temperature it is set to. Associated values are a perfect solution to this situation.

    enum OvenState {
        case on(Double)
        case off
    }

    var ovenState = OvenState.on(450)

Each case of an enumeration can have data of any type associated with it. For OvenState, its on case has an associated Double that represents the oven’s temperature. Notice that not all cases need to have associated values.

Retrieving the associated value from an enum is often done using a switch statement.

    switch ovenState {
    case let .on(temperature):
        print("The oven is on and set to (temperature) degrees.")
    case .off:
        print("The oven is off.")
    }

Note that the on case uses a let keyword to store the associated value in the temperature constant, which can be used within the case clause. (You can use the var keyword instead if temperature needs to be a variable.) Considering the value given to ovenState, the switch statement above would result in the line The oven is on and set to 450 degrees. printed to the console.

In the next section, you will use an enumeration with associated values to tie the result status of a request to the Flickr web service with data. A successful result status will be tied to the data containing interesting photos; a failure result status will be tied with error information.

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

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