Swift 3 Protocol-Oriented Programming Second Edition Build fast and powerful applications with the power of protocol-oriented programming Jon Hoffman BIRMINGHAM - MUMBAI Swift 3 Protocol-Oriented Programming Second Edition Copyright © 2016 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, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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. First published: February 2016 Second edition: November 2016 Production reference: 1231116 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78712-994-8 www.packtpub.com Credits Author Copy Editor Jon Hoffman Safis Editing Reviewer Project Coordinator Andrea Prearo Shweta H Birwatkar Commissioning Editor Proofreader Ashwin Nair Safis Editing Acquisition Editor Indexer Smeet Thakkar Aishwarya Gangawane Content Development Editor Graphics Sumeet Sawant Disha Haria Technical Editor Production Coordinator Egan Lobo Nilesh Mohite About the Author Jon Hoffman has over 20 years of experience in the field of information technology. Over those 20 years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon 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. What really drives Jon is the challenges the information technology field provides and there is nothing more exhilarating to him than overcoming a challenge. You can follow Jon on his two blogs: http://masteringswift.blogspot.com and http ://myroboticadventure.blogspot.com. Some of Jon’s other interests are watching baseball (Go Sox) and basketball (Go Celtics). Jon also really enjoys Tae Kwon Do where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter is currently working towards her black belt. I would like to thank my wonderful wife, Kim, without whose support, encouragement, patience, and understanding, this book would have never been written. I would also like to thank my two wonderful daughters, Kailey and Kara, who have both been my inspiration and driving force since the days they were born. About the Reviewer Andrea Prearo is a software engineer with over 15 years of experience. He is originally from Italy, and after a decade of writing software in C/C++ and C#, he moved to the Bay Area in 2011 to start developing mobile apps. In the last few years, he has been focusing on Swift, Objective-C, iOS, and microservices, with some short explorations of the Android platform. Currently, he is a member of the iOS development team at Capital One, working on the company’s flagship mobile banking app. His interests include reading books, watching movies, and hiking. From time to time, he also blogs about tech on Medium: https://medium.com/@andrea.prearo. I would like to thank my wonderful wife, Nicole, for her never-ending support in all my endeavors. www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. 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.PacktPub.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.PacktPub.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. https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Table of Contents Preface 1 Chapter 1: Object-Oriented and Protocol-Oriented Programming 7 What is object-oriented programming? 8 Requirements for the sample code 9 Swift as an object-oriented programming language 10 Drawbacks to object-oriented design 17 Swift as a protocol-oriented programming language 18 Summarizing protocol-oriented programming and object-oriented programming 25 Differences between object-oriented programming and protocol- oriented programming 26 Protocol and protocol extensions compared with superclasses 27 Implementing vehicle types 30 The winner is… 31 Summary 32 Chapter 2: Our Type Choices 33 The class 35 The structure 36 Access controls 37 The enumerations 38 The tuple 43 Protocols 45 Value and reference types 45 Recursive data types for reference types only 51 Inheritance for reference types only 54 Swift's built-in data types and data structures 56 Summary 58 Chapter 3: Catching Our Errors 59 Using the guard statement 60 Error handling 63 Error handling with return values 63 Error handling with do-catch 66 Representing errors 66 Throwing errors 68 Catching errors 71 Using the defer statement 74 When to use error handling 74 Summary 76 Chapter 4: All About the Protocol 77 Protocol syntax 79 Defining a protocol 79 Property requirements 80 Method requirements 81 Optional requirements 81 Protocol inheritance 82 Protocol composition 83 Using protocols as a type 86 Polymorphism with protocols 88 Type casting with protocols 89 Associated types with protocols 90 Delegation 93 Designing and developing with protocols 96 Summary 100 Chapter 5: Lets Extend Some Types 101 Defining an extension 102 Protocol extensions 105 Text validation 110 Summary 117 Chapter 6: Working with Generics 118 Generic functions 119 Type constraints with generics 122 Generic types 123 Associated types 127 Generics in a protocol-oriented design 128 Summary 133 Chapter 7: Adopting Design Patterns in Swift 134 What are design patterns? 135 Creational patterns 136 The singleton design pattern 137 Understanding the problem 137 Understanding the solution 138 [ ii ] Implementing the singleton pattern 138 The builder design pattern 140 Understanding the problem 140 Understanding the solution 140 Implementing the builder pattern 141 The factory method pattern 146 Understanding the problem 146 Understanding the solution 146 Implementing the factory method pattern 147 Structural design patterns 150 The bridge pattern 150 Understanding the problem 150 Understanding the solution 151 Implementing the bridge pattern 151 The facade pattern 155 Understanding the problem 155 Understanding the solution 155 Implementing the facade pattern 156 The proxy design pattern 158 Understanding the problem 158 Understanding the solution 159 Implementing the proxy pattern 159 Behavioral design patterns 161 The command design pattern 162 Understanding the problem 162 Understanding the solution 162 Implementing the command pattern 162 The strategy pattern 165 Understanding the problem 165 Understanding the solution 165 Implementing the strategy pattern 165 The observer pattern 167 Understanding the problem 167 Understanding the solution 168 Implementing the observer pattern 168 Summary 173 Chapter 8: Case Studies 174 Logging service 175 Requirements 176 The design 176 Conclusion 185 Data access layer 186 Requirements 186 [ iii ]