Methods

Recall that a method is a function that is associated with a type. In some languages, methods can only be associated with classes (which we will discuss in Chapter 15). In Swift, methods can also be associated with enums. Create a new enum that represents the state of a lightbulb.

Listing 14.18 Lightbulbs can be on or off

...
enum Lightbulb {
    case on
    case off
}

One of the things you might want to know is the temperature of the lightbulb. (For simplicity, assume that the bulb heats up immediately when it is turned on and cools off to the ambient temperature immediately when it is turned off.) Add a method for computing the surface temperature.

Listing 14.19 Establishing temperature behaviors

... enum Lightbulb ...

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.