O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required