Mastering Swift 4 Fourth Edition An in-depth and comprehensive guide on modern programming techniques with Swift Jon Hoffman BIRMINGHAM - MUMBAI Mastering Swift 4 Fourth Edition Copyright © 2017 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: June 2015 Second edition: November 2015 Third edition: October 2016 Fourth edition: September 2017 Production reference: 1250917 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78847-780-2 www.packtpub.com Credits Author Copy Editor Jon Hoffman Safis Editing Reviewer Project Coordinator Arthur Ariel Sabintsev Ulhas Kambali Commissioning Editor Proofreader Ashwin Nair Safis Editing Acquisition Editor Indexer Reshma Raman Rekha Nair Content Development Editor Graphics Vikas Tiwari Abhinash Sahu Technical Editor Production Coordinator Subhalaxmi Nadar Melwyn D'sa About the Author Jon Hoffman has over 25 years of experience in the field of information technology. Over these 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. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon is the challenges that the field of information technology provides, and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon's other interests are spending time with his family, robotic projects, and 3D printing. 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, Kara, is currently working toward her black belt. About the Reviewer Arthur Ariel Sabintsev is one of the lead iOS engineers at The Washington Post. His mobile engineering career includes working for a U.S. government-funded digital identity startup (ID.me), a Techstars-funded video startup (Shelby.tv), and an award winning mobile development agency (Fueled). He's spent the last 4 years teaching Swift and Objective-C for General Assembly and Betamore. He also maintains over a dozen open source iOS libraries and has made contributions to the Swift language and to the Swift Source Compatibility Suite. Before leaving his PhD program, he was an experimental nuclear physicist who worked underground colliding subatomic and subnuclear particles. 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 Customer Feedback Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788477804. If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products! Table of Contents Preface 1 Chapter 1: Taking the First Steps with Swift 6 What is Swift? 6 Swift features 8 Playgrounds 10 Getting started with Playgrounds 10 iOS, tvOS, and macOS Playgrounds 14 Showing images in a Playground 15 Creating and displaying graphs in Playgrounds 20 What Playgrounds are not 21 Swift language syntax 22 Comments 22 Semicolons 25 Parentheses 26 Curly brackets 27 An assignment operator does not return a value 28 Spaces are optional in conditional and assignment statements 29 Hello World 29 Summary 31 Chapter 2: Learning about Variables, Constants, Strings, and Operators 32 Constants and variables 33 Defining constants and variables 34 Type safety 36 Type inference 37 Explicit types 37 Numeric types 38 Integer types 38 Floating-point and Double values 41 The Boolean type 42 The string type 43 Optional variables 47 Optional binding 50 Optional chaining 51 Enumerations 53 Operators 57 The assignment operator 57 Comparison operators 58 Arithmetic operators 58 The remainder operator 59 Compound assignment operators 59 The ternary conditional operator 60 The logical NOT operator 60 The logical AND operator 60 The logical OR operator 61 Summary 61 Chapter 3: Using Swift Collections and the Tuple Type 62 Swift collection types 63 Mutability 63 Arrays 64 Creating and initializing arrays 64 Accessing the array elements 66 Counting the elements of an array 67 Is the array empty? 68 Appending to an array 68 Inserting a value into an array 69 Replacing elements in an array 69 Removing elements from an array 69 Merging two arrays 70 Retrieving a subarray from an array 70 Making bulk changes to an array 71 Algorithms for arrays 72 Sort 72 Sorted 73 Filter 73 Map 74 forEach 75 Iterating over an array 75 Dictionaries 76 Creating and initializing dictionaries 77 Accessing dictionary values 77 Counting the key or values in a dictionary 78 Is the dictionary empty? 78 Updating the value of a key 78 Adding a key-value pair 79 [ ii ]