November 2016
Intermediate to advanced
480 pages
14h 42m
English
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 ...
Read now
Unlock full access