Understanding extensions
Extensions allow you to provide extra capabilities to an object without modifying the original object definition. You can use them on Apple-provided objects (where you don’t have access to the object definition) or when you wish to segregate your code for readability and ease of maintenance. Here’s what an extension looks like:
class ExistingType {
property1
method1()
}
extension ExistingType : ProtocolName {
property2
method2()
}
Here, an extension is used to provide an additional property and method to an existing class.
For more information on extensions, visit: https://docs.swift.org/swift-book/LanguageGuide/Extensions.html.
Let’s look at how to use extensions. You’ll start by making the Sauce
enumeration conform to the CalorieCount
protocol using an extension in the next section.
Adopting a protocol via an extension
At present, the Sauce
enumeration does not...