Swift Data Structure and Algorithms Master the most common algorithms and data structures, and learn how to implement them efficiently using the most up-todate features of Swift Erik Azar Mario Eguiluz Alebicto BIRMINGHAM - MUMBAI Swift Data Structure and Algorithms 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 authors, 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: November 2016 Production reference: 1111116 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78588-450-4 www.packtpub.com Credits Authors Copy Editor Erik Azar Safis Editing Mario Eguiluz Alebicto Reviewer Project Coordinator Doug Sparling Ritika Manoj Commissioning Editor Proofreader Kunal Parikh Safis Editing Acquisition Editor Indexer Shweta Pant Rekha Nair Content Development Editor Graphics Divij Kotian Jason Monteiro Technical Editor Production Coordinator Prashant Mishra Shraddha Falebhai About the Authors Erik Azar is a computer scientist with over 20 years of professional experience of architecting and developing scalable, high-performance desktop, web, and mobile applications in the areas of network engineering, system management and security, and enterprise business services, having worked in diverse positions in companies ranging from startups to Fortune 500 companies He has been developing applications on macOS and iOS since attending his first WWDC in 2007, when Apple announced the initial iPhone Erik is an expert developer and architect for Availity, LLC, based in Jacksonville, Florida, where he works with teams to deliver software solutions in the healthcare industry Erik has performed technical reviews for several Packt Publishing books on Java RESTful APIs and security, enjoying the experience so much he decided to write his first book for Packt Publishing When Erik is not being a geek, he enjoys spending time with his wife, Rebecca, and his three kids, and getting out to ride his motorcycle up and down the Florida coast I want to thank my children, Patrick, Kyra, and Cassandra; my parents; and especially my wife, Rebecca, for their support and encouragement while writing this book I’d also like to thank Michael Privat and Robert Warner for their support, encouragement, and guidance on this project as well Lastly, I want to thank Mario, Divij, Prashant, and our technical reviewers for all of their hard work and guidance working on this book It’s been a great experience working with all of you Mario Eguiluz Alebicto is a software engineer with over 10 years of experience in development He started developing software with Java, switched later to Objective-C when the first iPhone delighted the world, and now he is also working with Swift He founded his own startup to develop mobile applications for small companies and local shops He has developed apps for different Fortune 500 companies and also for new disrupting startups since 2011 Now, he is working as a contractor in mobile applications, while writing technical and teaching materials whenever possible Apart from software development, Mario loves to travel, learn new things, play sports, and has considered himself a hardcore gamer since he was a child I want to thank my mother and sister for their love and unconditional support Borja, you helped me so much when I needed it Gloria, thanks for keeping me positive beyond my limits Also want to thank Divij, Erik, and the entire team for their guidance and work on this book You guys are awesome! About the Reviewers Doug Sparling works as a technical architect and software developer for Andrews McMeel Universal, a publishing and syndication company in Kansas City, MO At AMU, he uses Go for web services, Python for backend services, Ruby on Rails and WordPress for website development, and Objective-C, Swift, and Java for native iOS and Android development AMU’s sites include www.gocomics.com, www.uexpress.com, www.puzzlesociety.com, and www.dilbert.com He also was the co-author of a Perl book, Instant Perl Modules, for McGraw-Hill, and a reviewer for other Packt Publishing books, including jQuery 2.0 Animation Techniques: Beginner’s Guide and WordPress Web Application Development Doug has also played various roles for Manning Publications as a reviewer, technical development editor, and proofer, working on books such as Go in Action, The Well-Grounded Rubyist 2nd Edition, iOS Development with Swift, and Programming for Musicians and Digital Artists 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 service@packtpub.com 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 Chapter 1: Walking Across the Playground What is the importance of data structures? Data structures + algorithms = programs Interactive Playgrounds The Swift REPL Fundamental data structures Contiguous data structures Arrays Declaring an array Retrieving elements Adding elements Removing elements Linked data structures Singly linked list Overview of data structures Overview of algorithms Data types in Swift Value types and reference types Named and compound types Type aliases Collection types in the Swift standard library Asymptotic analysis Order of growth Summary Chapter 2: Working with Commonly Used Data Structures Using the Swift standard library Why structures? Declaring arrays in Swift Initializing array Adding and updating elements in an array Retrieving and removing elements from an array Retrieving and initializing dictionaries Initializing a dictionary Adding/modifying/removing a key-value pair Retrieving values from a dictionary 7 9 11 11 11 12 13 15 16 17 18 18 19 20 20 21 22 22 23 24 30 31 32 32 34 36 36 37 38 39 39 40 Declaring sets Initializing a set Modifying and retrieving elements of a set Set operations Comparison operations Membership and equality operations Characteristics of tuples Unnamed tuples Named tuples Implementing subscripting Subscript syntax Subscript options Understanding mutability and immutability Mutability of collections Interoperability between Swift and Objective-C Initialization Swift type compatibility Bridging collection classes NSArray to Array NSSet to set NSDictionary to dictionary Swift protocol-oriented programming Dispatching Protocol syntax Protocols as types Protocol extensions Examining protocols for use in collections Array literal syntax Making an array enumerable Sequence/IteratorProtocol Summary Chapter 3: Standing on the Shoulders of Giants Iterators, sequences, and collections Iterators Sequences Collections Stack Applications Implementation Protocols Queue [ ii ] 44 44 45 46 46 47 49 49 50 52 52 52 52 53 54 55 57 60 61 61 62 62 62 63 63 64 64 65 66 66 67 68 69 69 69 70 70 71 72 73 76 .. .Swift Data Structure and Algorithms Master the most common algorithms and data structures, and learn how to implement them efficiently using the most up-todate features of Swift Erik... the cursor to the end of the current line Delete Delete the character to the left of the cursor Esc < Move the cursor to the start of the first line Esc > Move the cursor to the end of the last... and libraries to help them create amazing new products At the end of the day, these APIs, which provide a level of abstraction, boil down to their use of data structures and algorithms Data structures