Swift Protocol-Oriented Programming - Jon Hoffman - E-Book

Swift Protocol-Oriented Programming E-Book

Jon Hoffman

0,0
28,14 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Embrace the Protocol-Oriented Programming paradigm, for better code maintainability and increased performance, with Swift programming.




Key Features



  • Leverage the power of Protocol-Oriented Programming in your applications


  • Leverage generics to create very flexible frameworks


  • Learn how to implement common design patterns in a protocol-oriented way





Book Description



Protocol-oriented programming is an incredibly powerful concept at the heart of Swift's design. Swift's standard library was developed using POP techniques, generics, and first-class value semantics; therefore, it is important for every Swift developer to understand these core concepts and take advantage of them. The fourth edition of this book is improved and updated to the latest version of the Swift programming language.






This book will help you understand what protocol-oriented programming is all about and how it is different from other programming paradigms such as object-oriented programming. This book covers topics such as generics, Copy-On-Write, extensions, and of course protocols. It also demonstrates how to use protocol-oriented programming techniques via real-world use cases.






By the end of this book, you will know how to use protocol-oriented programming techniques to build powerful and practical applications.





What you will learn



  • Learn the differences between object-oriented programming and protocol-oriented programming


  • Understand why value types should be prioritized over reference types


  • Delve into protocols, protocol inheritance, protocol composition, and protocol extensions


  • Learn how to implement COW (Copy-On-Write) within your custom value types


  • Understand how memory management works in Swift and how to avoid common pitfalls


  • Design applications by starting with the protocol rather than the implementation





Who this book is for



This book is intended for Swift developers who have, at minimum an introductory knowledge of the Swift programming language and would like to understand how they can use Protocol-Oriented Programming techniques in their applications.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 302

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Swift Protocol-Oriented ProgrammingFourth Edition

 

Increase productivity and build faster applications with Swift 5

 

 

 

 

 

 

 

 

 

 

 

 

Jon Hoffman

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Swift Protocol-Oriented Programming Fourth Edition

Copyright © 2019 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor:Kunal ChaudhariAcquisition Editor:Larissa PintoContent Development Editor:Arun NadarSenior Editor: Jack CummingsTechnical Editor:Jinesh TopiwalaCopy Editor: Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer:Rekha NairProduction Designer:Shraddha Falebhai

First published: February 2016 Second edition: November 2016 Third edition: October 2017 Fourth edition: June 2019

Production reference: 1280619

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78934-902-3

www.packtpub.com

 

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the author

Jon Hoffman has over 20 years' experience in the field of Information Technology. Over those 20 years, Jon has worked in the system administration, network administration, network security, application development, and architecture arenas. Currently, he works as an Enterprise Software Manager at Syntech Systems. He has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. Some of Jon's other interests are playing basketball, kayaking, and working out with his daughters. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter earned their black belts together early in 2014 and are currently 3rd-degree Black Belts.

With this being the fourth edition of this book, I would like to thank everyone that has given me encouragement, positive feedback, and constructive criticism though the years. That includes family, friends, co-workers, and everyone at Packt.

About the reviewers

Nikola Brežnjak is an engineer at heart and a jack of all trades. Currently, he's the director of engineering at Teltech, where he is responsible for the management, mentoring, and coaching of mobile app developers. He loves his job! He has written books on the Ionic framework and the MEAN stack, and has been a technical reviewer for a number of Packt books. He likes to help out on Stack Overflow, where he's a top contributor. He records a podcast called DevThink with his friend, Shawn Milochik, and runs a local meetup called MeCoDe.

I would like to thank my wife for supporting me in all my geeky endeavors and my parents for teaching me the power of hard and consistent work.

 

 

Vinod Madigeri is a senior software engineer with expertise in full-stack app development. He received his master’s in computer science from the University of Utah in 2015. He has worked in several industries (telecommunications, game technologies, and consumer electronics) as a developer, team leader, and mentor, writing software—in C, C++, Python, Objective-C, and Swift—for macOS and iOS platforms.

Currently, he spends much of his time exploring machine learning as a skill to complement his software development efforts.

Vinod has also been a technical reviewer for Mastering Swift 5, Object­–Oriented Programming with Swift, Hands-On Full-Stack Development with Swift, and Multiplayer Game Development with HTML5.

 

I'd like to thank my wife, Shruti, for her constant support, encouragement, and vanguard thoughts.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Swift Protocol-Oriented Programming Fourth Edition

About Packt

Why subscribe?

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Starting with the Protocol

Protocol syntax

Defining a protocol

Property requirements

Method requirements

Optional requirements

Protocol inheritance

Protocol composition

Using protocols as a type

Polymorphism with protocols

Type casting with protocols

Associated types with protocols

Delegation

Designing with protocols

Protocols in the Swift standard library

Summary

Our Type Choices

Classes

Structures

Access controls

Enumerations

Tuples

Protocols

Value and reference types

Recursive data types for reference types only

Inheritance for reference types only

Dynamic dispatch

Swift's built-in types

COW

Summary

Extensions

Defining an extension

Protocol extensions

Text validation

Extensions with the Swift standard library

Conforming to the Equatable protocol

Summary

Generics

Generic functions

Type constraints with generics

Generic types

Associated types

Generic subscripts

COW

Generics in a protocol-oriented design

Generics in the Swift standard library

Summary

Memory Management

How ARC works

Strong reference cycles

Unowned references

Weak references

Summary

Object-Oriented Programming

What is object-oriented programming?

Requirements for the sample code

Swift as an object-oriented programming language

Class diagrams

Object-oriented design

Vehicle superclass

Vehicle subclasses

Polymorphism

Issues with object-oriented design

Summary

Protocol-Oriented Programming

Requirements for the sample code

Swift as a protocol-oriented programming language

Protocol inheritance

Protocol composition

Protocol extensions

The Vehicle protocol

Vehicle implementations

Summarizing protocol-oriented programming and object-oriented programming

Differences between object-oriented programming and protocol-oriented programming

Protocol and protocol extensions compared with superclasses

Implementing vehicle types

Using value and reference types

The winner is...

Summary

Adopting Design Patterns in Swift

What are design patterns?

Creational patterns

The singleton design pattern

Understanding the problem

Understanding the solution

Implementing the singleton pattern

The builder design pattern

Understanding the problem

Understanding the solution

Implementing the builder pattern

The factory method pattern

Understanding the problem

Understanding the solution

Implementing the factory method pattern

Structural design patterns

The bridge pattern

Understanding the problem

Understanding the solution

Implementing the bridge pattern

The facade pattern

Understanding the problem

Understanding the solution

Implementing the facade pattern

The proxy design pattern

Understanding the problem

Understanding the solution

Implementing the proxy pattern

Behavioral design patterns

The command design pattern

Understanding the problem

Understanding the solution

Implementing the command pattern

The strategy pattern

Understanding the problem

Understanding the solution

Implementing the strategy pattern

The observer pattern

Understanding the problem

Understanding the solution

Implementing the observer pattern

Summary

Case Studies

Logging services

Requirements

The design

Conclusion

The data access layer

Requirements

The design

The data model layer

The data helper layer

The bridge layer

Using the data-access layer

Conclusion

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Apple announced Swift 2 at the World Wide Developers Conference (WWDC) in 2015. They also declared that Swift was the world's first protocol-oriented programming language. Judging by the name, someone might assume that protocol-oriented programming is all about the protocol or is simply object-oriented programming under a different name. These assumptions would be wrong. Protocol-oriented programming is about so much more than just the protocol; it is actually a new way of not only writing applications but thinking about the design of our application.

In the first five chapters of this book, we take an in-depth look at each of the components of the protocol-oriented programming paradigm. These chapters are designed to give you a solid understanding of the different components of protocol-oriented programming, so that you can understand how to use these components in your applications. One of the biggest misconceptions about protocol-oriented programming is that it is just another name for object-oriented programming. In Chapter 6, Object-Oriented Programming, and Chapter 7, Protocol-Oriented Programming, we take on this myth by comparing protocol-oriented programming to object-oriented programming to see what is similar and what is different. We also discuss the advantages and disadvantages of both programming paradigms.

The last two chapters are written to help you understand how you can design your application in a protocol-oriented programming way. Chapter 8, Adopting Design Patterns in Swift, looks at how we can implement several design patterns in a protocol-oriented way, and Chapter 9, Case Studies, looks at three real-world case studies to reinforce everything previously discussed in the book.

Who this book is for

This book is intended for the developer who has at least an introductory knowledge of the Swift programming language and wants to understand what protocol-oriented programming is. This book is written for the developer who not only wants to understand protocol-oriented programming but also wants to fully understand the different components of the programming paradigm. This book is written for the developer who learns best by looking at and working with code, because every concept covered in the book is backed by example code written to give you a solid understanding of the current topic and to demonstrate how to properly implement it.

What this book covers

Chapter 1, Starting with the Protocol, looks at what protocols are and how they are used in the Swift programming language. We will also examine how protocols can be used to write very flexible and reusable code.

Chapter 2, Our Type Choices, discusses the different types that Swift offers (structs, classes, enums, and tuples). We will look at several examples of when to use the various types and when not to.

Chapter 3, Extensions, looks at how extensions and protocol extensions are used with the Swift programming language. We will look at examples of how extensions can be used with protocol-oriented programming.

Chapter 4, Generics, shows how powerful generics are. Apple has stated that Generics are one of the most powerful features of Swift. We will look at how to use Generics to make very flexible types, and also how to implement the Copy-on-Write (COW) feature for our custom types.

Chapter 5, Memory Management, looks at how Swift manages memory with Automatic Reference Counting (ARC) and how strong reference cycles can cause ARC to fail. We also look at how to use weak and unowned references.

Chapter 6, Object-Oriented Programming, examines how we would develop characters for a video game if we were taking an object-oriented approach. In order to really appreciate the ideas behind protocol-oriented programming, we need to understand the problems it is designed to solve. We will then look at the drawbacks with this design.

Chapter 7, Protocol-Oriented Programming, develops the same video game characters from Chapter 5, Memory Management, but this time we will take a protocol-oriented approach to the design. We will then compare the object-oriented approach and the protocol-oriented approach to see the advantages that the protocol-oriented approach offers.

Chapter 8, Adopting Design Patterns in Swift, looks at implementing several design patterns using protocol-oriented programming. For each of the design patterns, we will look at the problem they are designed to solve and how to implement the pattern.

Chapter 9, Case Studies, explores two case studies. This chapter is designed to pull everything from the first six chapters together to show you how to use protocol-oriented programming in real-world situations.

To get the most out of this book

To follow along with the examples in this book, you will need to have an Apple computer with OS X 10.14 or higher installed. You will also need to install Xcode version 10.2 or higher with Swift version 5 or higher. You should possess at least a basic knowledge of the Swift programming language and how to use the development tools on their environment.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Swift-5-Protocol-Oriented-Programming-Fourth-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "To define the protocol, we use the protocol keyword, followed by the name of the protocol."

A block of code is set as follows:

struct MyStruct: MyProtocol { //Structure implementation here }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

Initializing class with name One

Initializing class with name Two

Setting class1ref1 to nil

Releaseing class with name One

Setting class2ref1 to nil

Setting class2ref2 to nil

Releaseing class with name Two

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "If we run this example, we will see that the Notification Received message."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Starting with the Protocol

This book is all about protocol-oriented programming. When Apple announced Swift 2 at the World Wide Developers Conference (WWDC) in 2015, they also declared that Swift was the world's first protocol-oriented programming language. From its name, we may assume that protocol-oriented programming is all about the protocol; however, this would be incorrect. Protocol-oriented programming is about so much more than just the protocol; it's actually a new way of not only writing applications, but also how we think about application design.

In this chapter, you will learn about the following topics:

How to define property and functional requirements within a protocol

How to use protocol inheritance and composition

How to use a protocol as a type

What is 

polymorphism?

How to use associated types with protocols

How to implement the delegation pattern with protocols

How to design type requirements with protocols

If you are coming from an object-oriented programming background, you may be familiar with the interface. In the object-oriented world, for most languages, the interface is a type that contains method and property signatures but does not contain implementation details. An interface can be considered a contract where any type that conforms to the interface must implement the required functionality defined within it. Most object-oriented developers rarely use interfaces as the focal point for their application design unless they are working with a framework similar to the Open Service Gateway Initiative (OSGi) framework. In protocol-oriented programming, the protocol is the focal point of your design.

When we are designing an application in an object-oriented way, we usually begin by focusing on the class hierarchy and how the objects interact. The object is a data structure that contains information about the attributes of the object in the form of properties, and the actions performed by or to the object in the form of methods. We cannot create an object without a blueprint that tells the application what attributes and actions to expect from the object. In most object-oriented languages, this blueprint comes in the form of a class. A class is a construct that allows us to encapsulate the properties and actions of an object into a single type.

Designing an application in a protocol-oriented way is significantly different from designing it in an object-oriented way. Rather than starting with the class hierarchy, protocol-oriented design says that we should start with the protocol. While protocol- oriented design is about so much more than just the protocol, we can think of the protocol as its backbone. After all, it would be pretty hard to have protocol-oriented programming without the protocol.

A protocol in Swift is similar to the interface in object-oriented languages, where the protocol acts as a contract that defines the methods, properties, and other requirements that are needed by our types to perform their tasks. We say that the protocol acts as a contract because any type that conforms to the protocol promises to implement the requirements defined by the protocol itself. If a type says that it conforms to a protocol and it doesn't implement all the functionality defined by the protocol, we will get a compile-time error and the project will not compile. In Swift, any class, structure, or enumeration can conform to a protocol.

We've just mentioned that the protocol is similar to the interface. Don't be fooled by this comparison because even though the interface and the protocol are similar, protocols in Swift are actually far more powerful than the interface in most object-oriented languages. As you read this book, you will find out how powerful Swift protocols can be.

Most modern object-oriented programming languages implement their standard library with a class hierarchy; however, the basis of Swift's standard library is the protocol (http://swiftdoc.org). Therefore, not only does Apple recommend that we use the protocol-oriented programming paradigm in our applications, but to also use it in the Swift standard library.

With the protocol being the basis of the Swift standard library and also the backbone of the protocol-oriented programming paradigm, it is very important that we fully understand what the protocol is and how we can use it. In this chapter, we will cover not only the basics of the protocol but also provide an understanding on how it can be used in application design.

Protocol syntax

In this section, we will look at how to define a protocol and how to add requirements to it. This will give us a basic understanding of the protocol. The rest of this chapter will build on this understanding.

Defining a protocol

The syntax we use to define a protocol is very similar to the syntax that's used to define a class, structure, or enumeration. The following example shows the syntax that's used to define a protocol:

protocol MyProtocol { //protocol definition here }

To define the protocol, we use the protocol keyword, followed by the name of the protocol. We then put the requirements, which our protocol defines, between curly brackets. Custom types can state that they conform to a particular protocol by placing the name of the protocol after the type's name, separated by a colon. The following example shows how we would define that a structure conforms to a protocol:

struct MyStruct: MyProtocol { //Structure implementation here }

A type can also conform to multiple protocols. We list the multiple protocols that the type conforms to by separating them with commas:

struct MyStruct: MyProtocol, AnotherProtocol, ThirdProtocol { //Structure implementation here }

Having a type conform to multiple protocols is a very important concept within protocol- oriented programming, as we will see later in this chapter and throughout this book. This concept is known as protocol composition. Now, let's see how we would add property requirements to our protocol.

Property requirements

A protocol can require that the conforming types provide certain properties with specified names and types. The protocol doesn't say whether the property should be a stored or computed property because the implementation details are left up to the conforming types.

When defining a property within a protocol, we must specify whether the property is a read-only or a read-write property by using the get and set keywords. We also need to specify the property's type since we cannot use type inference in a protocol. Let's look at how we would define properties within a protocol by creating a protocol named FullName, as shown in the following example:

protocol FullName { var firstName: String {get set} var lastName: String {get set} }

In this example, we define two properties named firstName and lastName, which are read-write properties. Any type that conforms to this protocol must implement both of these properties. If we wanted to define the property as read-only, we would define it using only the get keyword, as shown in the following code:

var readOnly: String {get}

It is possible to define static properties by using the static keyword, as shown in the following example:

static var typeProperty: String {get}

Static properties are properties that are owned by the type and shared by all instances. This means that if one instance changes the value of this property, then the value changes for all instances. We will look at how to use static instances more when we look at the singleton pattern.

Now, let's look at how we would add method requirements to our protocol.

Method requirements

A protocol can require that the conforming types provide specific methods. These methods are defined within the protocol exactly as we define them within a class or structure, but without the curly brackets and method body. We can define that these methods are instance or type methods using the static keyword. Adding default values to the method's parameters is not allowed when defining the method within a protocol.

Let's add a method named getFullName() to the FullName protocol:

protocol FullName { var firstName: String {get set} var lastName: String {get set} func getFullName() -> String }

The FullName protocol now requires one method named getFullName() and two read- write properties named firstName and lastName.

For value types, such as the structure, if we intend for a method to modify the instances that it belongs to, we must prefix the method definition with the mutating keyword. This keyword indicates that the method is allowed to modify the instance it belongs to. The following example shows how to use the mutating keyword with a method definition:

mutating func changeName()

If we mark a method requirement as mutating, we don't need to write the mutating keyword for that method when we adopt the protocol with a reference (class) type. The mutating keyword is only used with value (structures or enumerations) types.

Optional requirements

There are times when we want protocols to define optional requirements. An optional requirement is a method or property that doesn't need to be implemented. To use optional requirements, we need to start off by marking the protocol with the @objc attribute.

It is important to note that only classes can adopt protocols that use the @objc attribute. Structures and enumerations cannot adopt these protocols.

To mark a property or method as optional, we use the optional keyword. The following example shows how we would create both an optional property and also an optional method:

@objc protocol Phone { var phoneNumber: String {get set} @objc optional var emailAddress: String {get set} func dialNumber() @objc optional func getEmail() }

If we are using the @objc attribute, as shown in the previous example, we cannot use the mutating keyword because it isn't valid for classes. Now, let's explore how protocol inheritance works.

Protocol composition

Protocol composition lets our types adopt multiple protocols. This is a major advantage that we get when we use protocols rather than a class hierarchy because classes, in Swift and other single-inheritance languages, can only inherit from one superclass. The syntax for protocol composition is the same as the syntax for protocol inheritance that we just saw. The following example shows how we would use protocol composition:

struct MyStruct: ProtocolOne, ProtocolTwo, Protocolthree { //implementation here }

Protocol composition allows us to break our requirements into many smaller components rather than inheriting all the requirements from a single protocol or single superclass. This allows our type families to grow in width rather than height, which means we avoid creating bloated types that contain requirements that are not needed by all conforming types. Protocol composition may seem like a very simple concept, but it is a concept that is essential to protocol-oriented programming. Let's look at an example of protocol composition so that we can see the advantage we get from using it.

Let's say that we have the class hierarchy that's shown in the following diagram:

In this class hierarchy, we have a base class named Athlete. The Athlete base class then has two subclasses named Amateur and Pro. These classes are used depending on whether the athlete is an amateur athlete or a pro athlete. An amateur athlete may be a collegiate athlete, and we would need to store information such as which school they go to and their GPA. A pro athlete is one that gets paid for playing the game. For the pro athletes, we would need to store information such as what team they play for and their salary.

In this example, things get a little messy under the Amateur and Pro classes. As we can see, we have separate football player classes under both the Amateur and Pro classes (the AmFootballPlayer and ProFootballPlayer classes). We also have separate baseball classes under both the Amateur and Pro classes (the AmBaseballPlayer and ProBaseballPlayer classes). This means we need to have a lot of duplicate code between these classes.

With protocol composition, instead of having a class hierarchy where our subclasses inherit all the functionality from a single superclass, we have a collection of protocols that we can mix and match in our types:

We can then use one or more of these protocols as needed for our types. For example, we can create an AmFootballPlayer structure that conforms to the Athlete, Amateur, and FootballPlayer protocols. We could then create the ProFootballPlayer structure that conforms to the Athlete, Pro, and FootballPlayer protocols. This allows us to be very specific about the requirements for our types and only adopt the requirements that we need.

From a pure protocol point of view, this example may not make a lot of sense right now because protocols only define the requirements; however, in Chapter 3, Extensions, we will look at how protocol extensions can be used to implement these types with minimal duplicate code.

One word of warning: if you find yourself creating numerous protocols that only contain one or two requirements in them, then you are probably making your protocols too granular. This will lead to a design that is hard to maintain and manage.

Now, let's look at how a protocol is a full-fledged type in Swift.