Adopting a protocol via an extension

Let's make the Sauce enumeration conform to CalorieCountProtocol using extensions.

 Add the following code after the declaration for Sauce:

// Sauce enum
enum Sauce {
case chili
case tomato
}

// Sauce adopting CalorieCountProtocol via extension
extension Sauce : CalorieCountProtocol {
// enums can't have stored variables, only computed variables
var calories : Int {
switch self {
case .chili:
return 20
case .tomato:
return 15
}
}
func description() -> String {
return "This sauce has (calories) calories"
}
}

As you can see, no changes are made to the declaration for Sauce. You just added the required properties and methods to conform to CalorieCountProtocol in an extension. This is also really useful if you want to extend the capabilities of existing Swift types.

Enumerations can't have stored properties, so a switch statement is used to return the number of calories. The description() method is the same as the one in Burger and Fries.

At this point, all three food items have a calories property and a description() method. Great!

Let's see how we can put them in an array and perform an operation to get the total calorie count.

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

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