Protocol extensions
Protocol extensions allow us to extend a protocol to provide method and property implementations to conforming types. They also allow us to provide common implementations to all the conforming types, eliminating the need to provide an implementation in each individual type or the need to create a class hierarchy. While protocol extensions may not seem too exciting, once you see how powerful they really are, they will transform the way you think about and write code.
Let's begin by looking at how we would use protocol extensions within a very simplistic example. We will start by defining a protocol named Dog
, as follows:
protocol Dog {
var name: String { get set }
var color: String { get set }
}
With this protocol, we state that any type that conforms to the Dog
protocol must have the two properties of the String
type, named name
and color
. Next, let's define the three types that conform to this Dog
protocol. We will name these types...