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 confirming 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 extension with a very simplistic example. We will start off by defining a protocol called DogProtocol
as follows:
protocol DogProtocol { var name: String {get set} var color: String {get set} }
With this protocol, we are saying that any type that conforms to the DogProtocol
protocol, must have the two properties of the String type, with names of name
and color
. Now let's define the three types that conform to this protocol. We...