Creating an array of different types of objects

Ordinarily, it is not possible to create an array of different object types. However, since Burger, Fries, and Sauce all conform to CalorieCountProtocol, we can make an array that contains them:

  1. Type in the following code after all of the protocol and object declarations and run it. Since all of the food items conform to the CalorieCountProtocol protocol, you can add them to foodArray.
// create instances of each type
let burger = Burger()
let fries = Fries()
let sauce = Sauce.tomato

// print the descriptions
print(burger.description())
print(fries.description())
print(sauce.description())

// since all items have adopted the same protocol, you can add them
to a single array
let foodArray : [CalorieCountProtocol] = [burger, fries, sauce]
  1. All you need to do is to use a loop to calculate the total calorie count. Add in the following code after the line where you created the array and run the code:
// calculate the total number of calories
var totalCalories = 0
for food in foodArray {
totalCalories += food.calories
}
print(totalCalories)

The calories value for each food item will be successively added to totalCalories, and the total amount, 1315, will be displayed in the Debug area.

For more information on extensions, visit https://docs.swift.org/swift-book/LanguageGuide/Extensions.html.

This concludes the section on protocols and extensions. Let's look at error handling next, which looks at how to respond to or recover from errors in your program.

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

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