Book Image

Swift 4 Protocol-Oriented Programming - Third Edition

By : Jon Hoffman
Book Image

Swift 4 Protocol-Oriented Programming - Third Edition

By: Jon Hoffman

Overview of this book

Swift has become the number one language used in iOS and macOS development. The Swift standard library is developed using protocol-oriented programming techniques, generics, and first-class value semantics; therefore, every Swift developer should understand these powerful concepts and how to take advantage of them in their application design. This book will help you understand the differences between object-oriented programming and protocol-oriented programming. It will demonstrate how to work with protocol-oriented programming using real-world use cases. You will gain a solid knowledge of the various types that can be used in Swift and the differences between value and reference types. You will be taught how protocol-oriented programming techniques can be used to develop very flexible and easy-to-maintain code. By the end of the book, you will have a thorough understanding of protocol-oriented programming and how to utilize it to build powerful and practical applications.
Table of Contents (15 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Generic types


A generic type is a class, structure, or enumeration that can work with any type, just like Swift arrays and optionals can work with any type. When we create an instance of our generic type, we specify the type that the instance will work with. Once a type is defined, it cannot be changed for that instance.

To demonstrate how to create a generic type, let's create a simple List class. This class will use a Swift array as the backend storage and will let us add items or retrieve values from the list.

Let's begin by seeing how to define our generic List type:

struct List<T> { 
} 

The preceding code defines the generic List type. We can see that we use the <T> tag to define a generic placeholder, just like we did when we defined a generic function. This T placeholder can then be used anywhere within the type instead of a concrete type definition.

To create an instance of this type, we would need to define the type of items that our list will hold. The following examples...