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

Extending Exercise

A natural question to ask about an instance of Exercise is how many calories were burned per minute of exercise. You can use your knowledge of generics and where clauses to write a function that will perform that calculation.

Listing 23.4 Computing calories burned per minute, generically

...
func caloriesBurnedPerMinute<E: Exercise>(for exercise: E) -> Double {
    return exercise.caloriesBurned / exercise.minutes
}

print(caloriesBurnedPerMinute(for: ellipticalWorkout))
print(caloriesBurnedPerMinute(for: runningWorkout))

caloriesBurnedPerMinute(for:) is a generic function whose placeholder type is required to be a type that conforms to the Exercise protocol. You made caloriesBurnedPerMinute(for:) generic so that ...

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