(This page has no text content)
Learn Swift by Building Applications Emil Atanasov BIRMINGHAM - MUMBAI
Learn Swift by Building Applications Copyright 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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. Commissioning Editor: Ashwin Nair Acquisition Editor: Reshma Raman Content Development Editor: Nikhil Borkar Technical Editor: Madhunikita Sunil Chindarkar Copy Editor: Safis Editing Project Coordinator: Ulhas Kambali Proofreader: Safis Editing Indexer: Pratik Shirodkar Graphics: Tania Dutta Production Coordinator: Arvindkumar Gupta, Nilesh Mohite First published: May 2018 Production reference: 1230518 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78646-392-0
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content 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 and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details. At , 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.
Contributors About the author Emil Atanasov is an IT consultant who has extensive experience with mobile technologies. He started working in the field of mobile development in 2006. He runs his own contracting and consulting company, serving clients from around the world Appose Studio Inc. He is an MSc graduate from RWTH Aachen University, Germany, and Sofia University "St. Kliment Ohridski", Bulgaria. He has been a contractor for several large companies in the US and UK, serving variously as team leader, project manager, iOS developer, and Android developer. I want to thank my wife Elena, my family, and my friends for being very supportive, really patient, and super cool. Thank you for keeping me motivated through the endless work days. I know that in your eyes I'm a bizarre geeky person, who is spending most of the time in the digital world. I appreciate your understanding.
About the reviewer Giordano Scalzo is a developer with 20 years of programming experience, since the days of ZXSpectrum. He has worked in C++, Java, .Net, Ruby, Python, and in a ton of other languages that he has forgotten the names of. After years of backend development, over the past 5 years, Giordano has developed extensively for iOS, releasing more than 20 apps apps that he wrote for clients, enterprise application, or on his own. Currently, he is a contractor in London where, he delivers code for iOS through his company, Effective Code Ltd, aiming at quality and reliability. I d like to thank my better half, Valentina, who lovingly supports me in everything I do: without you, none of this would have been possible. Thanks to my bright future, Mattia and Luca, for giving me lots of smiles and hugs when I needed them. Finally, my gratitude goes to my mum and dad, who gave me curiosity and the support to follow my passions, which began one day when they bought me a ZXSpectrum. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Table of Contents Preface 1 Chapter 1: Swift Basics – Variables and Functions 6 Variables 7 Optional types 12 Enumeration types 13 Basic flow statements 14 The if statements – how to control the code flow 14 Loops 15 The while loops 16 The switch statement 17 Functions 19 What is a tuple? 21 What is the guard statement? 23 How to tackle huge problems – bottom-up versus top-down 23 Summary 25 Chapter 2: Getting Familiar with Xcode and Playgrounds 26 Installing Xcode 26 Exploring Xcode 29 What do we see on the screen? 31 Toolbar 31 Menu 35 The Navigator panel (located to the left) 37 The Debug panel (located at the bottom) 38 The Utilities panel (located to the right) 39 Xcode preferences window 41 Playground 44 What is a playground? 44 Let's add some code 45 How to add auxiliary code to a playground 52 How to add resource to a playground 52 Converting a playground to a workspace 53 Markup in playgrounds 54 Different items in the markup language 54 Basic markup items 56 Summary 59 Chapter 3: Creating a Minimal Mobile App 60 Your first iOS application 61 Project structure 74
Table of Contents [ ii ] AppDelegate 74 Application states 76 ViewController 77 Git 79 Summary 83 Chapter 4: Structures, Classes, and Inheritance 84 Structures and classes 84 Extensions 91 The deinit method 94 Type properties and functions 94 Adding custom data types to a playground 96 Inheritance 100 Base class 100 Class properties 103 Model-View-Controller (MVC) 104 Summary 108 Chapter 5: Adding Interactivity to Your First App 109 Storyboards 109 Visual components 111 Adding items to the storyboard 118 Linking the UI with the code 122 General discussion 138 Summary 139 Chapter 6: How to Use Data Structures, OOP, and Protocols 140 Primary collection types 140 Generics 141 Array 142 Set 144 Dictionary 148 How to choose the best collection type 150 List of items in a playground 151 UICollectionView 151 UICollectionViewCell 154 Reusing cells 157 Layouts 159 Table view in iOS app 163 Model list of cities 165 Displaying all cities 167 Adding search 172 Protocols 175 Protocols and inheritance 177 Summary 180 Chapter 7: Developing a Simple Weather App 181
Table of Contents [ iii ] Defining the app screens 182 The home screen 188 Favorite locations 192 Constraints 194 Picking a location 196 Model 198 Locations 207 Controllers and segues 212 The first segue 212 How to pass data 215 Passing information in the reverse direction 217 Defining a custom segue 218 Further improvements 219 Summary 220 Chapter 8: Introducing CocoaPods and Project Dependencies 221 Software – the modern way 222 Ruby and CocoaPods 223 How to use it 224 CocoaPods useful commands 228 Carthage 229 Swift Package Manager 230 Useful commands 231 Popular third-party libraries 237 Alamofire 238 Texture 239 RxSwift 240 Summary 241 Chapter 9: Improving a Version of a Weather App 242 Weather forecast API 243 What's an API? 243 List of requests 245 Creating new models 247 Pure network requests 250 Alamofire implementation 256 Improvements using third-party libraries 259 Better error handling 261 About the screen 263 Summary 267 Chapter 10: Building an Instagram-Like App 268 Tabbed app project 268 Firebase 269 Login 271 The different screens 278
Table of Contents [ iv ] Custom buttons on the tab bar 279 Creating a post 282 Models 288 Firebase 290 Filters 295 Summary 297 Chapter 11: Instagram-Like App Continued 298 Home screen 298 Profile screen 304 Search screen 312 Favorites screen 316 Polishing the home screen 318 Summary 330 Chapter 12: Contributing to an Open Source Project 331 Your account at GitHub 331 Forking a repository 332 Let's contribute 333 Pull request 335 Summary 338 Other Books You May Enjoy 340 Index 343
Preface Learning Swift 4 by Building Applications is a book that teaches the basics of Swift in the context of iOS. If you finish the book, you should be able to develop small-to-medium mobile apps. You will know how to create the app UI in storyboard using Xcode, how to load and display images fetched from the cloud, how to save and load information between different sessions of the app, and how to share data between all users of the app using the cloud. Who this book is for The book is designed for beginners who have little or no experience with Swift or any other programming language. The first couple of chapters introduce the Swift and the core programming principals, which are used throughout the process of software development. The rest of the book discusses the Swift development of iOS mobile applications. We will explain how to use open source libraries to achieve rapid software development and develop apps that are consuming information and images from the cloud. What this book covers , Swift Basics Variables and Functions, discusses the basics of the Swift language, starting from the A, B, and C. , Getting Familiar with Xcode and Playgrounds, presents the Xcode a free IDE that we will use when developing Swift. We shouldn't forget that Xcode is developed by Apple and that the playgrounds are the perfect place for learning Swift step by step. , Creating a Minimal Mobile App, makes you examine the minimal mobile app and its structure. This is the basis of every iOS mobile app written in Swift. , Structures, Classes, and Inheritance, covers the benefit of different data structures and how easily we can model a real-world problems. , Adding Interactivity to Your First App, looks at the different ways to add interactivity to an app or how to interact with the user in the app.
Preface [ 2 ] , How to Use Data Structures, OOP, and Protocols, explores the data structures and different techniques to incorporate them in our solutions. , Developing a Simple Weather App, focuses on how to build a real mobile app starting from the UI and displaying static data. , Introducing CocoaPods and Project Dependencies, introduces the modern way of rapid development using various dependency managers of Swift libraries. , Improving a Version of a Weather App, discusses about consuming information from the public API and displaying it in our Weather app. , Building an Instagram-Like App, builds an app from the idea step by step starting with the design, defines the basic UI, and connects it with a real cloud service provider Firebase. , Instagram-Like App Continued, makes the app complete and functional so that it can look like a working product, ready to be shared with users. , Contributing to an Open Source Project, takes you through the basics of contributing to an open source project. To get the most out of this book You have to know what is a computer and have basic knowledge of how to use a Mac. You have to be curious about how things work. We will start from the basics of the Swift programming language and Xcode. Most of the book is related to iOS, and it would be nice to have an iOS device to see your mobile applications working on a real device. You need enough time and patience to go through the book and to experiment with the code, which can be found on GitHub. Download the example code files You can download the example code files for this book from your account at . If you purchased this book elsewhere, you can visit and register to have the files emailed directly to you.
Preface [ 3 ] You can download the code files by following these steps: Log in or register at .1. Select the SUPPORT tab.2. Click on Code Downloads & Errata.3. Enter the name of the book in the Search box and follow the onscreen4. instructions. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: WinRAR/7-Zip for Windows Zipeg/iZip/UnRarX for Mac 7-Zip/PeaZip for Linux The code bundle for the book is also hosted on GitHub at . In case there's an update to the code, it will be updated on the existing GitHub repository. We also have other code bundles from our rich catalog of books and videos available at . Check them out! Download the color images We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it from . Conventions used There are a number of text conventions used throughout this book. : Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "This code creates a place in the memory, called , where we store the text, ."
Preface [ 4 ] A block of code is set as follows: When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: let let let let Any command-line input or output is written as follows: swift package init --type library Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Also, add an action to the Sign In With Email button." Warnings or important notes appear like this. Tips and tricks appear like this. Get in touch Feedback from our readers is always welcome. General feedback: Email and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at .
Preface [ 5 ] Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit , selecting your book, clicking on the Errata Submission Form link, and entering the details. Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit . Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit .
1 Swift Basics – Variables and Functions In this chapter, we will present the basics of the Swift language, starting from square one: introducing the basic concepts. The code, which is part of the chapter, illustrates the topics under discussion. In the next chapter, we will learn how to execute code samples in Xcode. Let's begin with a brief history of Swift. This is a brand new programming language, developed by Apple and announced in 2014. In 2016, Swift 3 was released as open source, and this is the first major version, which enables people interested in Swift to develop the language. This means only one thing: Swift will start spreading even faster, beyond Apple's ecosystem. In this book, we will give examples of Swift, and we will discuss most of our solutions related to iOS, but you should know that the knowledge here is applicable across all places where Swift code is used. Before diving into real code, let's define some basic concepts that we can use later in the book. What is a computer program or application (app)? Simply, we can think of an app as a set of computer instructions that can be executed. Each app has a source code, written in a language describing all actions that the program does. In our case, we will write mobile (iOS) apps in Swift. There are many low-level computer instructions, but Swift helps us to write without hassle, without knowing much about the low-level organization. Now we will start with the basic concept of variables.
Swift Basics – Variables and Functions Chapter 1 [ 7 ] We will discuss the following topics: Constants and variables Initializing using expressions Basic types in Swift Optional types Enumeration types Code flow statements , , loops Functions Tuples The statement Top-down and bottom-up We begin with the basic building blocks of all programs. Variables What is a variable? This is a place in the memory where we can store some data and use it later in our program. A good example is if you want to take an action based on a user's input, then the input should be stored somewhere on the device (computer). Usually, this place is in the device's memory. To let our program know that we need such a place, we have to express that. A statement is used. In Swift, declaring a variable looks like this: var This code creates a place in the memory, called , where we store the text, . Later, we can use it to carry out some meaningful actions. An advantage of a variable is that it can be changed later to contain a different value. Here, we should be careful Swift is pretty strict about types (this will be discussed later), and, thus, we can't mix different value types. There are strict rules that should be followed, and we will get familiar with these soon. So, in our case, we can do the following to change the text that is stored in our variable, named :
Swift Basics – Variables and Functions Chapter 1 [ 8 ] Now we know what a variable is and how to work with variables. Let's try to do some calculations using variables, with stored integer values: var var var In the preceding code, we have created three variables. The first two were initialized with literal expressions, or simply with exact values. In the code, we can use complex calculations, and the Swift compiler will handle this case easily as follows: var This is the same as the previous code snippet. The last variable is initialized with the value of the expression . To calculate this expression, the compiler uses the values stored in the previously declared variables (on the previous lines). The evaluation happens once the code is executed. What does this mean: The evaluation happens once the code is executed? In short, if or contain different values, then the variable will reflect this. The code is working with the names of the places in memory, but the actual result depends on the values stored there. We could read the preceding code like this: Create a place in the memory, which we will call , and store the value in it Create a place in the memory, which we will call , and store the value in it Create another place in the memory, called , and store the value of the expression of what's stored in plus what's stored in Usually, we use variables to allocate places in memory, which we will modify in the following code. But we don't always want to change the value of a variable once it is set. Thus, to simplify it, there is a special word in Swift, , which denotes a place in the memory that won't be changed in the future. Its value is set initially and it can't be changed. (This is slightly different when we are working with objects, but this will become clear later in the book.)
Swift Basics – Variables and Functions Chapter 1 [ 9 ] The following code defines a place in memory that won't be updated. If we try to update it, then the Swift compiler will inform us that it is not possible. The value on the left is a constant and we are trying to change it: let The exact error is: , which means that we are trying to set a new value to a constant. Let's see how we can update our previous code snippets, once we know that there are and keywords. The first code with the variable should be the same, because we change the value of the variable . The second code, with the sum of two integers, could be rewritten as follows: let let let A good practice is to keep using whenever possible. The compiler gives us hints all the time. Of course, it's possible to keep something stored in a variable instead of a constant while developing, but if we want to squeeze out every single bit of performance, then we should stick to the best practice replace all unmodified variables with constants. Why do we gain performance when using ? The short answer is, the compiler knows that this place in the memory will be used only for reading from operations, and it cuts all the extra logic, which is needed to support modifications. The developers can reason locally and don't need to foresee any future changes of this value, because it is immutable. Now we are familiar with variables, it's the perfect time to introduce the concept of a type. First, each variable has a type. The type defines the set of values which can be stored in a variable. Each type uses a different amount of the device's memory. Based on the type, the compiler knows how much space should be allocated when we declare a new variable. In Swift, we define the type of a variable after the declaration of the variable itself. Our first code would look like this: var
Swift Basics – Variables and Functions Chapter 1 [ 10 ] Is it mandatory to add a type declaration after each variable definition? No. The Swift compiler is quite smart, and it infers the types based on the expressions on the right side. There are many examples which could illustrate how smart it is. But we should remember one: if the variable or constant is initialized, then we can simply omit the type. Of course, explicitly pointing to the type will make the code easier for other developers to understand. It's good to keep the same code style through all your code across every project. For some projects, it could be better if the type is omitted; for some, it may be worse. Let's present all the basic types that Swift uses. The numbers are presented by several different types, based on the precision which is needed. The largest type takes extra memory, but it can store bigger values. The integer numbers can be stored in variables or constants from the following types: , , , , , , , and . Floating-point numbers can be of the following types: , , , and . We are already familiar with the type. It's used to store text in computer memory. Later, the text can be manipulated and presented to the user in different forms. The other quite popular data type is , which takes exactly two values or . We will discuss the need of boolean expressions later in this chapter, once we get familiar with conditional statements in Swift. We will define enumerable types and tuples. These are specific types that we can define, compared to the other ones, which are already defined for us. Until now, we could declare variables or constants in one particular way. There are advanced ways to do this one is to declare multiple variables on a single line, like this: var All variables are from the same type, namely, . We can specify a different type for each one, which gives us the freedom to declare variables/constants in a single shot on the same line. The following code is an example of this: var We can expand this even further by setting a default value, like in the following code: var
Comments 0
Loading comments...
Reply to Comment
Edit Comment