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

Type constraints with Generics


A type constraint specifies that a generic type must inherit from a specific class or conform to a particular protocol. This allows us to use the methods or properties defined by the parent class or protocol with the generic types. Let's look at how to use type constraints by rewriting the genericEqual() function to use the Comparable protocol:

func testGenericComparable<T: Comparable>(a: T, b: T) -> Bool{  
  return a == b 
} 

To specify the type constraint, we put the type or protocol constraint after the generic placeholder, where the generic placeholder and the constraint are separated by a colon. This new function works as we might expect, and it will compare the values of the two parameters and return true if they are equal or false if they are not.

We can declare multiple constraints just like we declare multiple generic types. The following example shows how to declare two generic types with different constraints:

func testFunction<T: MyClass...