-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
Protocol extensions enable us to extend a protocol in order to provide method and property implementations for conforming types. This enables us to provide common implementations for all the conforming types, eliminating the need to provide separate implementations for each individual type. While protocol extensions might not initially appear exciting, once you see how powerful they can really be, they will transform the way you think about and write code.
Let’s begin by looking at how we can use protocol extensions within a very simple example. We will start by defining a protocol named Dog, as shown here:
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 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 JackRussel...