Main Learn Swift by Building Applications: Explore Swift programming through iOS app development

Learn Swift by Building Applications: Explore Swift programming through iOS app development

Start building your very own mobile apps with this comprehensive introduction to Swift and object-oriented programming

Key Features
• A complete beginner's guide to Swift programming language
• Understand core Swift programming concepts and techniques for creating popular iOS apps
• Start your journey toward building mobile app development with this practical guide

Book Description
Swift Language is now more powerful than ever; it has introduced new ways to solve old problems and has gone on to become one of the fastest growing popular languages. It is now a de-facto choice for iOS developers and it powers most of the newly released and popular apps. This practical guide will help you to begin your journey with Swift programming through learning how to build iOS apps.
You will learn all about basic variables, if clauses, functions, loops, and other core concepts; then structures, classes, and inheritance will be discussed. Next, you'll dive into developing a weather app that consumes data from the internet and presents information to the user. The final project is more complex, involving creating an Instagram like app that integrates different external libraries. The app also uses CocoaPods as its package dependency manager, to give you a cutting-edge tool to add to your skillset. By the end of the book, you will have learned how to model real-world apps in Swift.

What you will learn
• Become a pro at iOS development by creating simple-to-complex iOS mobile applications
• Master Playgrounds, a unique and intuitive approach to teaching Xcode
• Tackle the basics, including variables, if clauses, functions, loops and structures, classes, and inheritance
• Model real-world objects in Swift and have an in-depth understanding of the data structures used, along with OOP concepts and protocols
• Use CocoaPods, an open source Swift package manager to ease your everyday developer requirements
• Develop a wide range of apps, from a simple weather app to an Instagram-like social app
• Get ahead in the industry by learning how to use third-party libraries efficiently in your apps

Who This Book Is For
This book is for beginners who are new to Swift or may have some preliminary knowledge of Objective-C. If you are interested in learning and mastering Swift in Apple's ecosystem, namely mobile development, then this book is for you.
Year: 2018
Edition: 1
Publisher: Packt Publishing
Language: english
Pages: 366 / 356
ISBN 13: 978-1786463920
ISBN: 178646392X
File: PDF, 9.66 MB
Download (pdf, 9.66 MB)
Preview

You may be interested in

 

Most frequently terms

 
 
You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
Learn Swift by Building
Applications

&YQMPSF4XJGUQSPHSBNNJOHUISPVHIJ04BQQEFWFMPQNFOU

Emil Atanasov

BIRMINGHAM - MUMBAI

Learn Swift by Building Applications
Copyright a 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

XXXQBDLUQVCDPN

NBQUJP

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 XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.
At XXX1BDLU1VCDPN, 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 worldbAppose 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
appsbapps 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 BVUIPSTQBDLUQVCDPN
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
Variables
Optional types

Enumeration types
Basic flow statements

The if statements – how to control the code flow
Loops
The while loops

The switch statement

Functions

What is a tuple?
What is the guard statement?
How to tackle huge problems – bottom-up versus top-down

Summary
Chapter 2: Getting Familiar with Xcode and Playgrounds
Installing Xcode
Exploring Xcode
What do we see on the screen?

Toolbar
Menu
The Navigator panel (located to the left)
The Debug panel (located at the bottom)
The Utilities panel (located to the right)
Xcode preferences window

Playground

What is a playground?
Let's add some code
How to add auxiliary code to a playground
How to add resource to a playground

Converting a playground to a workspace
Markup in playgrounds
Different items in the markup language
Basic markup items

Summary
Chapter 3: Creating a Minimal Mobile App
Your first iOS application
Project structure

6
7
12
13
14
14
15
16
17
19
21
23
23
25
26
26
29
31
31
35
37
38
39
41
44
44
45
52
52
53
54
54
56
59
60
61
74

Table of Contents

Git

AppDelegate
Application states
ViewController

Summary
Chapter 4: Structures, Classes, and Inheritance
Structures and classes
Extensions
The deinit method
Type properties and functions
Adding custom data types to a playground

Inheritance

Base class

Class properties

Model-View-Controller (MVC)

Summary
Chapter 5: Adding Interactivity to Your First App
Storyboards
Visual components
Adding items to the storyboard
Linking the UI with the code
General discussion

Summary
Chapter 6: How to Use Data Structures, OOP, and Protocols
Primary collection types
Generics
Array
Set
Dictionary
How to choose the best collection type

List of items in a playground
UICollectionView

UICollectionViewCell
Reusing cells
Layouts

Table view in iOS app
Model list of cities

Displaying all cities
Adding search

Protocols

Protocols and inheritance

Summary
Chapter 7: Developing a Simple Weather App
[ ii ]

74
76
77
79
83

84
84
91
94
94
96
100
100
103
104
108
109
109
111
118
122
138
139
140
140
141
142
144
148
150
151
151
154
157
159
163
165
167
172
175
177
180
181

Table of Contents

Defining the app screens
The home screen
Favorite locations
Constraints

Picking a location

Model

Locations
Controllers and segues

The first segue
How to pass data
Passing information in the reverse direction
Defining a custom segue

Further improvements

Summary
Chapter 8: Introducing CocoaPods and Project Dependencies
Software – the modern way
Ruby and CocoaPods
How to use it

CocoaPods useful commands

Carthage
Swift Package Manager
Useful commands

Popular third-party libraries
Alamofire
Texture
RxSwift

Summary
Chapter 9: Improving a Version of a Weather App
Weather forecast API
What's an API?
List of requests
Creating new models

Pure network requests

Alamofire implementation
Improvements using third-party libraries
Better error handling
About the screen

Summary
Chapter 10: Building an Instagram-Like App
Tabbed app project
Firebase
Login
The different screens

[ iii ]

182
188
192
194
196
198
207
212
212
215
217
218
219
220
221
222
223
224
228
229
230
231
237
238
239
240
241
242
243
243
245
247
250
256
259
261
263
267
268
268
269
271
278

Table of Contents

Custom buttons on the tab bar
Creating a post
Models
Firebase
Filters

Summary
Chapter 11: Instagram-Like App Continued
Home screen
Profile screen
Search screen
Favorites screen
Polishing the home screen
Summary
Chapter 12: Contributing to an Open Source Project
Your account at GitHub
Forking a repository
Let's contribute
Pull request
Summary
Other Books You May Enjoy
Index

279
282
288
290
295
297
298
298
304
312
316
318
330
331
331
332
333
335
338
340
343

[ iv ]

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
$IBQUFS, Swift Basics a Variables and Functions, discusses the basics of the Swift language,

starting from the A, B, and C.
$IBQUFS, Getting Familiar with Xcode and Playgrounds, presents the Xcodeba 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.
$IBQUFS, 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.
$IBQUFS, Structures, Classes, and Inheritance, covers the benefit of different data structures
and how easily we can model a real-world problems.
$IBQUFS, 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
$IBQUFS, How to Use Data Structures, OOP, and Protocols, explores the data structures and
different techniques to incorporate them in our solutions.
$IBQUFS, Developing a Simple Weather App, focuses on how to build a real mobile app

starting from the UI and displaying static data.
$IBQUFS, Introducing CocoaPods and Project Dependencies, introduces the modern way of

rapid development using various dependency managers of Swift libraries.
$IBQUFS, Improving a Version of a Weather App, discusses about consuming information

from the public API and displaying it in our Weather app.
$IBQUFS, 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
providerbFirebase.
$IBQUFS, 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.
$IBQUFS, 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
XXXQBDLUQVCDPN. If you purchased this book elsewhere, you can visit
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly to you.

[2]

Preface

You can download the code files by following these steps:
1.
2.
3.
4.

Log in or register at XXXQBDLUQVCDPN.
Select the SUPPORT tab.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box and follow the onscreen
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 IUUQTHJUIVCDPN1BDLU1VCMJTIJOH-FBSO4XJGUCZ#VJMEJOH"QQMJDBUJPOT. 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 IUUQTHJUIVCDPN1BDLU1VCMJTIJOH. 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 IUUQXXXQBDLUQVCDPNTJUFTEFGBVMUGJMFT
EPXOMPBET-FBSO4XJGUCZ#VJMEJOH"QQMJDBUJPOT@$PMPS*NBHFTQEG.

Conventions used
There are a number of text conventions used throughout this book.
$PEF*O5FYU: 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 UFYU, where we store the
text, )FMMPXPSME."

[3]

Preface

A block of code is set as follows:
GVODHFOFSBUF(SFFUJOH HSFFU4USJOHUIJOH4USJOHXPSME  4USJOH\
SFUVSOHSFFU UIJOH 
^
QSJOU HFOFSBUF(SFFUJOH HSFFU)FMMP
QSJOU HFOFSBUF(SFFUJOH HSFFU)FMMPUIJOH4XJGU

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
letOVNCFS
letEJWJTPS
letSFNBJOEFSOVNCFSEJWJTPSSFNBJOEFSJTBHBJOJOUFHFS
letRVPUJFOUOVNCFSEJWJTPSRVPUJFOUJTBHBJOJOUFHFS

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 GFFECBDL!QBDLUQVCDPN 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 RVFTUJPOT!QBDLUQVCDPN.

[4]

Preface

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 XXXQBDLUQVCDPNTVCNJUFSSBUB, 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 DPQZSJHIU!QBDLUQVCDPN 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
BVUIPSTQBDLUQVCDPN.

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 QBDLUQVCDPN.

[5]

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

We will discuss the following topics:
Constants and variables
Initializing using expressions
Basic types in Swift
Optional types
Enumeration types
Code flow statements c JG, TXJUDI, loops
Functions
Tuples
The HVBSE 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 WBS statement is used.
In Swift, declaring a variable looks like this:
varUFYU)FMMPXPSME

This code creates a place in the memory, called UFYU, where we store the text, )FMMP
XPSME. 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 carefulbSwift 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 UFYU:
UFYU)FZ*U T4XJGU

[7]

Swift Basics – Variables and Functions

Chapter 1

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 GJWF
var GPVS
var TVNGPVS GJWF

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 GJWF 

This is the same as the previous code snippet.
The last variable TVN is initialized with the value of the expression GPVS GJWF. 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 GPVS or GJWF
contain different values, then the TVN 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 GJWF, and store the value  in it
Create a place in the memory, which we will call GPVS, and store the value  in it
Create another place in the memory, called TVN, and store the value of the
expression of what's stored in GPVS plus what's stored in GJWF
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, MFU, 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.)

[8]

Swift Basics – Variables and Functions

Chapter 1

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:
letIFMMP8PSME)FMMP8PSME
IFMMP8PSME)FMMP4XJGU8PSMEUIFDPNQJMFSJTDPNQMBJOJOH

The exact error is: $BOOPUBTTJHOUPWBMVF IFMMP8PSME JTB MFU DPOTUBOU,
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 WBS
and MFU keywords.
The first code with the UFYU variable should be the same, because we change the value of
the variable UFYU. The second code, with the sum of two integers, could be rewritten as
follows:
let GJWF
let GPVS
let TVNGPVS GJWF

A good practice is to keep using MFU 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 practicebreplace all unmodified variables with constants.
Why do we gain performance when using MFU? 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 UFYU4USJOH)FMMP8PSME

[9]

Swift Basics – Variables and Functions

Chapter 1

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: *OU, *OU, *OU, *OU, *OU, 6*OU, 6*OU, and
6*OU. Floating-point numbers can be of the following types: 'MPBU, 'MPBU, 'MPBU,
and %PVCMF. We are already familiar with the 4USJOH 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 #PPM, which takes exactly two valuesbUSVF or
GBMTF. 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 thisbone is to declare multiple variables on a single line, like this:
varBCTVN%PVCMF

All variables are from the same type, namely, %PVCMF.
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:
varHSFFUJOH4USJOHBHF*OUNPOFZ%PVCMF

We can expand this even further by setting a default value, like in the following code:
varY%PVCMFC#PPMUSVF

[ 10 ]

Swift Basics – Variables and Functions

Chapter 1

Of course, Swift is smart enough, so the following code has the very same meaning:
varYCUSVF

This automatic process is called type inference and greatly reduces the unnecessary
boilerplate code which we would have to write.
Before diving into the details related to the different data types, we should know how to
add comments to our code. Comments are blocks of text which are part of the source code,
but they are removed when the source code is compiled.
The compilation is a complex process of transforming the code to machine
code (in the case of Swift, it's something like this: Swift is converted to
BitCode and this is converted to assembler, which is converted to machine
languageblow-level machine instructions which are understood by the
hardware and are executed pretty quickly).
The comment's role is to clarify the code. There are two types of comments that we can use
when we are developing a program in Swift. The first type is a single-row comment, which
starts with  (double slash) and continues until the end of the row. Usually, developers
prefer to start this comment on a new row or to add it to the end of a line, presenting a
detail about the code, so it's easier for the reader to understand the encoded programming
logic. The other type is a block comment, which starts with  (slash and asterisk) and ends
with  (asterisk and slash). The comment can start anywhere, and continues until the
matching ending sequence.
An interesting improvement from C++ or some other languages is that we
can have several comment blocks which are nested in other comment
blocks.
This is something new, which simplifies the process when we are adding comments.
When writing good code, try to add comments to make it easily
understandable. In most cases, naming the variables with explicit names
helps, but, usually, a brief comment is enough to clear the fog around a
pretty complex sequence of your code.

[ 11 ]

Swift Basics – Variables and Functions

Chapter 1

Optional types
We are familiar with basic types and their forms, but now it's time to introduce the optional
type(s). This is a new concept, compared to what we have in Objective-C, which helps
developers to avoid common mistakes when they are working with data. To explain the
optional type(s), we should present the problem they are solving.
When we are developing a program, we can declare a variable, and we should set it an
initial value. Later in the code, we can use it. But this is not applicable in general. There
may be some cases when the default value is to have /07"-6&, or simply OJM. This means
that when we want to work with a variable which has /07"-6&, we should check that. But
if we forget the check, then while our app is executed, we can reach this strange state with
/07"-6&, and the app usually crashes. Also, the code which checks whether a variable
contains a value is reduced, and the programming style is concise.
To summarize: optionals enforce better programming style and improve the code checking
when the compiler does its job.
Now let's meet the optional types in the following code snippet:
varGJWF0S/PUIJOH*OU
XFXJMMEJTDVTTUIFJGTUBUFNFOUMBUFSJOUIJTDIBQUFS
JGletGJWFGJWF0S/PUIJOH\
QSJOU GJWF 
^FMTF\
QSJOU 5IFSFJTOPWBMVF 
^
GJWF0S/PUIJOHOJM
XFXJMMEJTDVTTUIFJGTUBUFNFOUMBUFSJOUIJTDIBQUFS
JGletGJWFGJWF0S/PUIJOH\
QSJOU GJWF 
^FMTF\
QSJOU 5IFSFJTOPWBMVF 
^

Every type we know so far has an optional version, if we can call it that. Later in the book,
you will understand the whole magic behind the optional types; namely, how they are
created. Here are some of those: 4USJOH, #PPM, %PVCMF, 'MPBU, and so on.

[ 12 ]

Swift Basics – Variables and Functions

Chapter 1

Until now, we have learned how to store data, but we don't know what kind of actions we
can do with it. This is why we should get familiar with basic operations with the data. The
operations are denoted with operators such as , , , and . These operations work with
particular data types, and we have to do the conversion ourselves.
Let's check this code:
letOVNCFS
letEJWJTPS
letSFNBJOEFSOVNCFSEJWJTPSSFNBJOEFSJTBHBJOJOUFHFS
letRVPUJFOUOVNCFSEJWJTPSRVPUJFOUJTBHBJOJOUFHFS
letIFZ)J
letHSFFUJOH4XJGUIFZ 4XJGUPQFSBUPS DPODBUFOBUFTTUSJOHT

Enumeration types
In Swift, we can define simple types which have limited possible different values. These
types are enumerations. We define them with the keyword FOVN. The following code is an
example of this:
FOVN"O&OVNFSBUJPO\
UIFWBMVFEFGJOJUJPOTHPFTIFSF
^

Here's another code that does this:
FOVN(BNF*OQVU%FWJDF
DBTFLFZCPBSEKPZTUJDLNPVTF
^

The code has three different enumeration cases. All cases may appear on a single line, such
as in the preceding code, or even one by one on a line.
We can meet the following notation, because Swift infers the missing part:
varJOQVU(BNF*OQVU%FWJDFNPVTF

MBUFSJOUIFDPEF
JOQVUKPZTUJDL

[ 13 ]

Swift Basics – Variables and Functions

Chapter 1

The code bundle for the book is hosted on GitHub
at IUUQTHJUIVCDPN1BDLU1VCMJTIJOH-FBSO4XJGUCZ#VJMEJOH"QQ
MJDBUJPOT. In case there's an update to the code, it will be updated on the
existing GitHub repository.

Basic flow statements
What are basic flow statements? These are several statements which help you to structure
the program code in a way that allows you to do different action(s) based on the data stored
in particular variables. We will learn how to execute just part of the code if a certain
condition is met (the condition could be a pretty complex Boolean expression). Then, we
will find a way to execute different actions several times in a loop. The next thing will be to
learn how to repeat things until a condition is met and to stop executing statements once
the condition is not satisfied. Using flow-control statements, we can construct pretty
complex code chunks, similar to what we can express with regular text writing. To develop
a program, we should first create an algorithm (a sequence of steps) which leads to the
desired result, taking into account all external and internal conditions. Based on this
sequence, we can then develop a program, using all flow operators. But let's get familiar
with some forms of them.

The if statements ` how to control the code flow
This is how we can branch our code logic based on some data stored in a variable:
letOVN
JGOVN\
QSJOU 5IFOVNCFS= OVN JTFWFO
^FMTF\
QSJOU 5IFOVNCFS= OVN JTPEE
^

The general pattern of an JG statement is organized as follows:
var MPHJDBM$IFDL 
JG MPHJDBM$IFDL \
DPEFXIJDIXJMMCFFYFDVUFEJGUIFMPHJDBMDIFDLJTFWBMVBUFEUP
USVF
^FMTF\
DPEFXIJDIXJMMCFFYFDVUFEJGUIFMPHJDBMDIFDLJTFWBMVBUFEUP
GBMTF
^

[ 14 ]

Swift Basics – Variables and Functions

Chapter 1

We know that the JG clause gives us huge freedom to shape the code that will be executed
(evaluated). An application may handle many different cases, but only the code that fulfills
the conditions encoded in our solution will be triggered.

Loops
Let's learn how to implement repetitive tasks. There are several ways to do that, using
different loops: XIJMF, GPSJO, and SFQFBUXIJMF. The most popular one is the
GPSJO loop. Here is what the basic form looks like:
let DPMMFDUJPO<>
GPSWBSJBCMFJODPMMFDUJPO\
EPTPNFBDUJPO
^

The code will be interpreted like this: the variable will be set to all possible values, which
are stored in the collection. If the collection is empty, then no code will be executed. If there
are some elements, then the body of the loop (the code in curly braces) will be executed for
each element of the collection. The variable loops through every single element and can be
used in code.
We need an example to illustrate this. Let's use the following code to print all numbers
from  to , inclusive:
varTVN
GPSJOEFYJO\
TVN JOEFY
QSJOU  JOEFY 
^
QSJOU 4VN= TVN 
TVNJTFRVBMUP

The sum of all numbers from  to  is stored in a separate variable and the code prints
every single number on a new line. The sequence defined with  is converted to a
collection (we can think of it as an array), which is fueling the GPSJO loop.
We can use variables or constants to define custom ranges of numbers.

[ 15 ]

Swift Basics – Variables and Functions

Chapter 1

Take a look at the following code:
letUISFF5JNFT
GPS@JOUISFF5JNFT\
QSJOU 1SJOUUIJTNFTTBHF
^

Using @ (underscore) we declare that the argument should ignore the values set in the
variable, and it doesn't matter to the rest of the code. The code will print three times: 1SJOU
UIJTNFTTBHF.

The while loops
The XIJMF loops execute the body of the loop (list of the statements in the body part) until
the condition is evaluated to GBMTF.
There are two types of XIJMF loops. There is the classical XIJMF loop, which checks the
condition, and, if it holds, then the code in the body is executed. Then the check is
performed again and everything is repeated until the condition is evaluated to GBMTF. The
other variant is the SFQFBUXIJMF loop, which first executes the body, and then does the
check. The second type is executed at least once, compared to the first one, which could be
completely skipped:
varJ
letNBY
varTVN
XIJMFJNBY\
TVN J
J 
^
QSJOU 4VN= TVN 

The code sums all numbers from  to . The condition will be broken once J reaches .
We can use SFQFBUXIJMF to do the same:
WBSJ
MFUNBY
WBSTVN
SFQFBU\
TVN J
J 
^XIJMFJNBY
QSJOU 4VN= TVN 

[ 16 ]

Swift Basics – Variables and Functions

Chapter 1

We can use XIJMF to implement the SFQFBUXIJMF loops and the reverse, but with
slight modifications. The best rule for picking the right type of loop is to know whether the
sequence should be executed at least once. Executing once means that it's much easier to
implement it using SFQFBUXIJMF; otherwise, the classical XIJMF loop is the best choice.
There are some special conditions which we should handle, but to do so, let's see what they
are.
We can use the special wordsbDPOUJOVF and CSFBLbto trigger special behavior while we
are in a loop. The DPOUJOVF statement is used when you want to stop the current iteration
of the loop and start over. When using this, be careful that you change the value in the
condition; otherwise, the loop could be an infinite one, which means that your program
won't end.
The CSFBL statement is used once we want to stop the entire loop. Be careful when you
have nested loops. The CSFBL statement stops the current iteration immediately, and then
jumps to the very first line after the end of the innermost loop, which contains the
CSFBL statement. If you want to break two or more nested loops, then you have to find an
appropriate way to do so. To be explicit when breaking nested loops, you may use labeled
statements. It is a convenient way to give a name of a loop and then to change the flow
when using CSFBL. It's good to know that CSFBL may be used as part of a TXJUDI
statement. This will be discussed in the next part.
There are a few other special words, such as SFUVSO , UISPX, and GBMMUISPVHI which
change the default order of execution of the code. We will get familiar with these later.

The switch statement
A TXJUDI statement is a concise way to describe a situation where we have several possible
options to pick from and we don't want to write a lot of boilerplate code using the already
familiar JG statement.
Here is the general pattern of a TXJUDI statement (please note that this is not a valid Swift
code):
TXJUDIBWBSJBCMFUPCFNBUDIFE\
DBTFWBMVF
DPEFXIJDIXJMMCFFYFDVUFEJGWBSJBCMFIBTWBMVF
XFOFFEBUMFBTUPOFWBMJEFYFDVUBCMFTUBUFNFOUIFSF
 DPNNFOUTBSFOPUBOFYFDVUBCMFTUBUFNFOU
DBTFWBMVF
WBMVF

[ 17 ]

Swift Basics – Variables and Functions

Chapter 1

DPEFXIJDIXJMMCFFYFDVUFEJGWBSJBCMFIBTWBMVFPSWBMVF
EFGBVMU
DPEFXIJDIXJMMCFFYFDVUFEJGWBSJBCMFIBTWBMVFEJGGFSFOU
GSPNBMMMJTUFEDBTFT
^

What we see is that TXJUDI has many possible cases, each one starting with the special
word DBTF, and then a specific value. Swift supports specific value matching, but it
supports more complex rules for pattern matching. Each case could be considered as a
separate JG statement. If one case is activated, then all others are skipped. The EFGBVMU
case is a specific one and is triggered if there is no match with any other case. The EFGBVMU
case appears at the end, and it's defined with the special word EFGBVMU.
We can use CSFBL to interrupt execution of the code in a DBTF statement. If we want to
have an empty DBTF statement, it's good to add CSFBL.
We have some specifics with the implementation of TXJUDI in Swift, which are new when
compared to the other programming languages, but they improve the readability of the
code. First, there is now a way to have an empty body of a specific case. To be correct, we
have to add at least one valid statement after the case. There is no implicit fallthrough after
each case. This means that once the last executable statement in a DBTF branch is triggered,
we are continuing after the TXJUDI statement. Nothing else that is part of the
TXJUDI statement will be executed. We could consider that every DBTF statement has a
hidden break at its very end. Next, we need the special word GBMMUISPVHI to simulate the
regular behavior of the switch. Another interesting thing is that we can have interval
matching, tuples matching, and value bindings. Finally, we can use the XIFSF clause if we
want to express some dependency between the data which should be matched. It's also
possible to list several cases if they have to share the code which should be executed. They
have to be separated with .
Here is code that shows how easy and smart TXJUDI is:
letQPJOU 
TXJUDIQPJOU\
DBTFlet YZ XIFSFYZ
QSJOU 9JT= Y :JT= Z 5IFZIBWFUIFTBNFWBMVF 
DBTF letZ 
QSJOU 9JT:JT= Z 5IFZDPVMECFEJGGFSFOU 
DBTF letY 
QSJOU 9JT= Y :JT5IFZDPVMECFEJGGFSFOU 
DBTFlet YZ XIFSFY Z
QSJOU 9JT= Y :JT= Z 9JTHSFBUFSUIBO: 
EFGBVMU
QSJOU "SFZPVTVSF

[ 18 ]

Swift Basics – Variables and Functions

Chapter 1

^

Functions
In this section, we will learn how to define functions and how to use them in our code.
They help us to reuse sequences of statements with ease. We can define a general solution
of a problem and then apply it, customized, to different parts of our app. This approach
saves time, reduces the potential of bugs in the code, and simplifies huge problems to small
ones.
The first function, which we already saw in use, is QSJOU . It's used to display text on the
screen. We will experiment with this in the next chapter, once we get our hands dirty with
Xcode and Swift.
Now let's define our first function, which executes a sequence of statements in its body:
GVODQSJOU4VN \
letB
letC
QSJOU 4VN= B  = C = B C 
^

When defining a function, we start with the special word GVOD. Then the name of the
function follows and the list of the arguments in brackets  and its returned type. After
that comes the body of the function in curly braces \^.
The name can start with any letter or underscore and can be followed by a
letter, digit, underscore, or dollar sign. A function name shouldn't match
any keyword from the Swift language.
This definition doesn't do anything if we don't call (execute) the function. How is this done?
We have to call the function using its own name as follows:
QSJOU4VN

Once a function is called, we may think that the same sequence of code is executed where
the function call is made. It's not exactly the same, but we can think of having the body of
the function executed line by line.

[ 19 ]

Swift Basics – Variables and Functions

Chapter 1

Now let's see the general form of a function:
GVODGVODUJPO/BNF BSHVNFOU-BCFMWBSJBCMF/BNF4USJOH  4USJOH\
letSFUVSOFE7BMVFWBSJBCMF/BNF XBTQBTTFE
SFUVSOSFUVSOFE7BMVF
^
IFSFJTUIFGVODUJPOJOWPDBUJPOBOEIPXUIFSFTVMUJTSFUVSOFE
letSFTVMU0G'VODUJPO$BMMGVODUJPO/BNF BSHVNFOU-BCFM/PUIJOH

Each function may have no arguments, one argument, or many arguments. Until now, we
have seen some without arguments and with a single argument. Every argument has an
argument label and a parameter name. The argument label is used when the function is
called. This is really useful when we have many parameters. It gives us a clue what data
should be passed to that specific parameter when using the function. The parameter name
(variable name) is the name which will be used in the function body to refer to the passed
value. All parameters should have unique parameter names; otherwise there is ambiguity,
and we won't be able to say which one is which.
A function may return a value from a specific type, or it may be void (nothing will be
returned). When we want to return something, we have to define that, and this is done with
 and the type of the result. In the preceding code, we see  4USJOH, and this means that
the function returns a value of the 4USJOH type. This obliges/binds us to using the keyword
SFUVSO in the function body at least once. The SFUVSO keyword immediately stops the
execution of the function and returns the value passed. If a function doesn't return
anything, we can still use SFUVSO in its body, and it will work similarly to CSFBL in a loop.
We can use @ if we want to skip the label of an argument. Here is a simple piece of code
that illustrates that:
GVODDPODBUFOBUF4USJOHT @T4USJOH@T4USJOH  4USJOH\
SFUVSOT T
^
letIFMMP4XJGUDPODBUFOBUF4USJOHT )FMMP4XJGU
PS
DPODBUFOBUF4USJOHT )FMMP4XJGU

When we don't use the @ (underscore), then the argument name is the same as the
parameter name (variable name).
Similar to what we have seen with the labels, we can ignore the returned value once the
function is called.

[ 20 ]

Swift Basics – Variables and Functions

Chapter 1

What happens if we want to return multiple values? We can use tuples to return multiple
values when executing a function. The following code is an example of this:
EFGJOFBGVODUJPOXIJDIGJOETUIFNBYFMFNFOUBOEJUTJOEFYJOBO
BSSBZPGJOUFHFST
GVODNBY*UFN*OEFY OVNCFST<*OU>   JUFN*OUJOEFY*OU \
varJOEFY
varNBY*OUNJO
VTFUIJTGBODZOPUBUJPOUPBUUBDIBOJOEFYUPFBDIJUFN
GPS JWBM JOOVNCFSTFOVNFSBUFE \
JGNBYWBM\
NBYWBM
JOEFYJ
^
^
SFUVSO NBYJOEFY
^
letNBY*UFN5VQMFNBY*UFN*OEFY OVNCFST<>
JGNBY*UFN5VQMFJOEFY \
QSJOU .BYJUFNJT= NBY*UFN5VQMFJUFN 
^
QSJOUT.BYJUFNJT

What is a tuple?
A tuple is a bundle of different types (they may be the same) which have short names. In
the preceding code, we have a tuple of two *OU statements. The first one is named JUFN,
and the second one is named JOEFY. After the execution of the function, we will store the
maximum item and its index in the tuple. If there are no items in the array, then the index
will be .
It's possible to return an optional tuple type if there is a chance to return OJM in some cases.
The previous function may return OJM if there are no items, and a valid result otherwise.
Each parameter may have a default value set. To set a default value, you have to declare it
and add it right after the parameter's type. The following code is an example of this:
GVODHFOFSBUF(SFFUJOH HSFFU4USJOHUIJOH4USJOHXPSME  4USJOH\
SFUVSOHSFFU UIJOH 
^
QSJOU HFOFSBUF(SFFUJOH HSFFU)FMMP
QSJOU HFOFSBUF(SFFUJOH HSFFU)FMMPUIJOH4XJGU

[ 21 ]

Swift Basics – Variables and Functions

Chapter 1

We can easily define a function which accepts zero or more variables of a specified type.
This is called a variadic parameter. Each function definition could have, at most, one
variadic parameter. It's denoted with  after its type. In the body of the function, the type
of this parameter is converted to an array. This array contains all passed values:
GVODNBY7BMVF @OVNCFST*OU  *OU\
varNBY*OUNJO
GPSWJOOVNCFST\
JGNBYW\
NBYW
^
^
SFUVSONBY
^
QSJOU NBY7BMVF 
QSJOUT

One specific thing that we should know about function parameters is that they are
constants. We can't mutate these by mistake. We should express this explicitly. To do so, we
have to use the special word JOPVU to mark the parameter. The JOPVU parameters is added
before the type of the parameter. We can pass variables to the JOPVU parameters, but we
can't pass constants. To pass a variable, we should mark this with  when calling the
function. The JOPVU parameters can't have default values. Also, variadic parameters can't
be marked as such. In general, we can use the JOPVU parameters to return values from a
function, but this is not the same as returning values using SFUVSO. This is an alternative
way to let a function affect the outer world in the matrix. Check out the following code:
GVODVQEBUF7BS @YJOPVU*OUOFX7BMVF*OU \
YOFX7BMVF
^
varUFO
QSJOU UFO
VQEBUF7BS UFOOFX7BMVF
QSJOU UFO

[ 22 ]

Swift Basics – Variables and Functions

Chapter 1

What is the guard statement?
The HVBSE statement has similar behavior to an JG statement. This statement checks the
condition, and if it's not met, then the FMTF clause is triggered. In the FMTF clause, the
developer should finish the current function or program, because the prerequisites won't be
met. Take a look at the following code:
GVODHFOFSBUF(SFFUJOH @HSFFUJOH4USJOH  4USJOH\
HVBSEletHSFFUJOHHSFFUJOHFMTF\
UIFSFJTOPHSFFUJOHXFSFUVSOTPNFUIJOHBOEGJOJTI
SFUVSO/PHSFFUJOH 
^
UIFSFJTBHSFFUJOHBOEXFHFOFSBUFBHSFFUJOHNFTTBHF
SFUVSOHSFFUJOH 4XJGU
^
QSJOU HFOFSBUF(SFFUJOH OJM
QSJOU HFOFSBUF(SFFUJOH )FZ

This is a tiny example, showing us code that illustrates the regular usage of the HVBSE
statement. We can combine it with the XIFSF clause, or we can make the check really
complex. Usually, it's used when the code depends on several JGMFU checks. The
HVBSE statement keeps the code concise.

How to tackle huge problems ` bottom-up versus
top-down
Step-by-step through this book, we will start solving problems until we can write a fullyworking mobile app. It's not an easy task, but we can take two different approaches when
trying to solve a huge problem (such as writing a mobile app). The first one is top-down.
This technique starts from the top with the main problem, and breaks it down into smaller
problems and functions. Once we reach something unclear, something which is not well
defined that we should implement, then we define a new function, but we won't continue
developing the exact implementation of this part of the app immediately. Let's assume that
we are trying to develop a mobile app with three screens. The first one displays a list of
news. The second one renders specific news, and the last one shows information about our
application.

[ 23 ]

Swift Basics – Variables and Functions

Chapter 1

If we apply the top-down approach, then we will have the following abstract process. We
start from the biggest problem: how to develop an app with three screens. Then, we break
this huge task down into three sub-tasks with their respective functions. Those functions
are empty functions. The first one will be responsible for creating the first screen, the
second one should create the detailed news presentation, and the third should define the
last screen. By doing this, we have decomposed the main problem into three smaller ones.
These new functions are empty, but at a later phase we will implement each one of them.
We can start with the first one: we define another help function which creates the list of
news, and another function which fetches the news from an internet address. Now it
doesn't look really hard to define those functions. We will learn how to do this throughout
the book, but the general idea is to break down each problem into smaller ones until you
reach a state where you can solve them without any hassle. In the end, the main problem
will be solved, because all parts that have been decomposed are already working, and the
final result will be a fully-working mobile application.
The other approach is bottom-up, which does things in reverse. It's more like working with
Lego, but you first go and build many small building blocks, which you combine together
until you manage to build a solution to the whole problem; in our case, until you build a
working mobile app. Abstractly, we develop simple enough functions that we can
implement to solve small problems. Then we combine those into bigger chunks. Those
bigger chunks are put together in even bigger and more complex functions or app parts,
until we define the final working app.
Neither of these two approaches is the best. Every developer prefers to use a nice mixture
of both techniques, which leads to the final resultba working app.
If top-down, or bottom-up, is used on its own, it is not a silver bullet. Try
to use top-down and bottom-up together and you will find the solution
easier.
Just tweak your approach based on what you know at the moment, and what you have.

[ 24 ]

Swift Basics – Variables and Functions

Chapter 1

Summary
In this chapter, we became familiar with Swift 4 basics. We now know what variables and
constants are. We can use basic types, the JG and TXJUDI statements, and loops, and we
can define functions. These are the smallest key building blocks that we will need to start
our adventure in Swift 4 and the iOS/macOS/watchOS world.
In the next chapter, you will become familiar with Xcodebthe development environment
software that is really handy when we are writing code in Swift. You will develop your first
playground, which is a nice tool to check and demo the code. You can use everything
learned in this chapter, and, in the end, you will be familiar with how to add descriptions
using a markup language to make your playgrounds and functions well documented. Don't
spend a minute morebfind a macOS and move to the next chapter to get your hands dirty
with some real code.

[ 25 ]

2
Getting Familiar with Xcode and
Playgrounds
In this chapter, we will get familiar with Xcode, the Integrated Development Environment
(IDE) that is used to develop iOS, macOS, tvOS, and watchOS apps. We will introduce a
pretty neat way of playing with and exploring the Swift language called playground. We
will see all the panels and the many different options that are available in Xcode. We will
find an easy way to use templates and we will experiment with real Swift code in a
playground.
In this chapter, we will cover the following topics:
Installing Xcode
Exploring playground
Different options available in Xcode
Markup items

Installing Xcode
First, Xcode runs on macOS only. This means you have to find a macOS-compatible
computer that is running macOS 10.13 or later.
It is possible to have macOS running on a virtual machine, but having a
hardware one is better.

Getting Familiar with Xcode and Playgrounds

Chapter 2

We will install Xcode version 9.3. This is the latest version available in the App Store at the
moment, but it may change in the near future, so no worries if you install a slightly newer
version. The IDE looks the same way.
Start your computer and open the App Store application. This application is used to
download extra software on to your macOS. You can find its icon on the dock, as shown
here:

Once you've clicked the icon, you should see the App Store application displayed. At the
top-right corner, there is a search field. Select it and start typing 9DPEF. You will see many
suggestions as shown in the following screenshot:

[ 27 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Select the first item, which is what we are looking for. The next screen that will be
displayed is the search result screen, something similar to this:

The only difference will be that the button will say INSTALL instead of UPDATE. Xcode is
free software, provided by Apple, so you will be able to install it at no cost. Just press the
INSTALL button and the download process will be triggered. The initial installation may
take hours, based on your internet connection and computer speed. Don't worrybleave the
computer doing its own job and you can keep reading this chapter. Once the process has
finished successfully, you will see that the App Store displays another button, Open as
shown in the following screenshot:

[ 28 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

You have to click Open to start the Xcode. Another option is to find it in Applications
Installed and to click on the blue icon (you have seen the icon already, while installing).
The next section explores the Xcode application.

Exploring Xcode
The Xcode application is installed and it is running. You will see the following start screen:

On the right, you will see No Recent Projects, but this just shows a list of the last few
projects you have worked on. On the left, you will see the version of Xcode 9.3 and a few
shortcuts. We will start with the first one to get familiar with the playground. Go and click
Get started with a playground. A new window is displayed, as shown in the following
screenshot. Don't panic; this is the window in which you have to select the template for
your playground project. For now, we will stick to iOS:

[ 29 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

When you click Next, you have to enter the name of the playground. Let's start with 4XJGU
CZFYBNQMFT. We can change the platform if we want to explore the different features of
other platforms. Xcode has a really powerful simulator which can simulate different OS
(tvOS, iOS). The development for these platforms is a breeze once we know Swift.
You have to pick a folder to store the playground project. A good place is the %PDVNFOUT
folder, (click on it; it should be located on the left) and then you can create a
subfolder, 4XJGU, using the button at the bottom left, New Folder. Another option is to
pick a place on your own. Once you are ready, click on the Create button, which is located
at the bottom-right of this window. Xcode initiates a process and generates a simple
playground for us:

The Xcode windows looks a bit empty, but don't panic. It's because you should focus on the
development process, but this chapter is to get familiar with Xcode; that's why we will start
exploring the IDE. After the exploration part, we will get back to the playgrounds and why
they are cool.

[ 30 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

What do we see on the screen?
In this section, we will present all the important parts of the Xcode application, such as
panels, toolbars, buttons, and their use. Once you are ready, you will know where you can
find specific information about your project or how to find and edit a specific part of a
mobile project.

Toolbar
This is the topmost part of the screen. We have the status line, which says Ready | Today at
7:28 PM, as shown in the following screenshot. This is the place where Xcode
communicates with us. The app prints all errors here and we can dive into the details by
clicking on the errors. There are no errors at the moment, but they may appear at times.
Successful messages such as the one on the previous screen and the following screen can't
be explored:

We have the basic controls located on the right. There are two groups of buttons. The first
group consists of the following options:
Show the standard editor
: This option presents a single window to edit
the project (usually, a view of our source code).
Show the assistant editor
: This option splits the screen in two. There is a
small down arrow at the bottom of this option. Once you activate this mode, the
second click will present a menu with different options. You can explore all
possible options. We won't use this mode of the Xcode now. It will be explained
in detail later, when we are about to use it (this will happen when we start
developing the UI using storyboards).
Show the version editor
: This one is used when the project supports
versions and Git. (We will get briefly to this option once we discuss Git and
version control integration.)

[ 31 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The second group also has the following three buttons which activate advanced panels of
the Xcode. These are toggle buttons, which activate (show) or deactivate (hide) different
parts:
Hide or show the Navigator button
: This button activates the Navigator
panel, which is located to the left. Once activated, the editor (main part) is
squeezed. If it's deactivated, then the editor is expanded to take the whole
window estate as shown in the following screenshot:

For more information, check the sub-section which explains the Navigator panel.
Hide or show the Debug Area button
which is located at the bottom:

[ 32 ]

: This activates the Debug panel,

Getting Familiar with Xcode and Playgrounds

Chapter 2

For more information, check the sub-section which explains the Debug panel.
Hide or show the Utilities button
: This activates the Utilities panel, which
is located on the right as shown in the following screenshot:

For more information, check the subsection which explains the Utilities panel.
Each one of these three panels gives the user extra control of the project and an easy way to
change its configuration. We can add and explore all files and assets from the Navigation
panel. We see the output from the app in the Debug panel. There are too many buttons to
be clicked, which could lead to confusion. Don't try to remember everything now, just start
exploring the IDE and you will get used to it. Then you will learn the shortcut keys, and
step-by-step you will become an Xcode master.
The panels are contextual, which means they look different based on the
active (selected) file.

We can see the active file at the very top of the editor. In our case, 4XJGUCZFYBNQMFT,
as shown in the following screenshot:

[ 33 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The playground can contain many files and assets, but the main file is
displayed, once the playground is opened.

The Related Items button
provides a menu to explore all files, which have been
opened as shown in the following screenshot:

$POUFOUTTXJGU is the main file of every playground; it contains the
code which is executed when the playground is run.

The back arrow button helps us to go to the previous file that was explored in the editor. In
our case, when we have a playground with a single file, it's not very usable; but when we
start to build real mobile apps, then it will become handy.
The forward arrow button does the opposite of the back arrow button. You can use it to go
to the next file.
The filename, 4XJGUCZFYBNQMFT, is a visual tree that shows the playground project
structure. It's pretty close to what you will see in the Navigator panel. You can use it to
switch between different source files in the editor area as shown in the following
screenshot:

[ 34 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The rest of the editor area is used to render the selected file at the top. In our case, we see
the code of the playground project. To be more precise, the $POUFOUTTXJGU file. At the
very bottom, we see the Debug panel action bar. It looks like this:
There are two
buttons: the first one is to open the console, which triggers the Debug panel button in the
top-right part of the Xcode window (the middle button). The second is the Play button
which evaluates the whole playground. We can use it to run the code that we have written.
If we press it, the status bar (part of the toolbar) will start and will say Ready | Today at
12:00 PM (where the time will be your current time of execution).

Menu
Xcode has a menu bar, which is common to all the macOS software as shown in the
following screenshot:

We won't discuss all options from the preceding screenshot, but will try to briefly point out
the most important ones:
Xcode: You can open the preference window from this menu option Xcode |
Preferences... or by using (cmd + ,). The preference window can be used to
configure the Xcode so it suits you. It's really important to customize the IDE so
itds a friendlier place to spend the time with. For more information, check the
Xcode preferences window section. You can open different developer tools that
are part of the Xcode, such as Instruments or File Merge.
File: The following actions can be started:
New: This opens a new tab (Xcode supports many tabs), a new
project (Xcode can have several projects opened at one time), a
new window (one project can be edited in two different windows),
and so on
Open: This opens projects and triggers the Quickly Open
Windows tool, which helps you to jump without hassle through
the source code of the project when it is huge
Save: This saves files and projects
Close: This closes the files

[ 35 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Edit: A typical edit menu, containing Undo (cmd + Z) and Redo (cmd + Shift + Z),
is here, as well as copying and pasting items, and different types of filtering and
sorting.
View: Access to the different panels and their subtabs. Open the Xcode in fullscreen mode (cmd + Ctrl + F).
Find: Different options to find and/or replace text in a project.
Navigate: Use this to open different parts of the Xcode or to move around.
Editor: Various options to indent the text. Also, to insert different symbols.
Product: Triggers builds or tests. Everything related to building (compiling) a
project can be found here.
Debug: Different options to initiate a debug session. Please note that this is not
applicable to playground.
Source Control: Manage source files using Git. We will get familiar with this,
once we start working on mobile apps.
Window: Easy way to organize the Xcode windows, once there are several of
them.
Help: To find help about the Xcode or to access the language documentation.
The best place to get familiar with Xcode is to read what Apple has
prepared. Navigate to Help | Xcode to get detailed explanations about
each part of the Xcode.
Now let's get familiar with the basic options in the three main panels, starting with the
Navigator panel.

[ 36 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The Navigator panel (located to the left)
The Navigator panel displays the project structure on the left. It has root item(s). Usually,
this is the project and the project looks like a tree. We can use the arrows to expand each
level of this visual tree. Using right-click, we bring up a menu, where some handy shortcuts
are displayed as shown in the following screenshot:

[ 37 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The Navigator panel contains a bottom menu which has the following options:
+ button: To add new files to the project.
Filter text field: A textbox which can be used to filter the content of the
preceding list. For example, if we want to see all images which are the QOH files,
then we can simply enter 1/( in the filter. In our case, with the currently opened
playground, this will display the text No Filter Results.
Show only recent files: The clock icon, if itds activated, will show the recent files
only.
Show only files with source control status: The square icon, if active will
display the files under Source Control (included in the Git repository).
The Navigator panel has four tabs when we are exploring the playground project. It has a
few more when the project is a mobile one.
The first tab is the project navigator, as we already know. The next is the symbol navigator,
the place where we can explore the source code structure. (Don't panicbwe will learn how
to create all these structures and will be able to use this panel.) The third is the find
navigator, the place that is used when we want to locate something in a project, not only in
the source files. This tab contains different options to tweak the search. Don't be afraid;
explore them to narrow down what you are looking for.
The last tab is the issue navigator. In this tab, we have a list of all build-time and runtime
issues caused by our project.
At the bottom, there is a filter on each tab, which is similar to the one we had discussed
earlier. You can use it to filter the results presented in the tab.

The Debug panel (located at the bottom)
The Debug panel is located at the bottom of the Xcode. While developing a playground
project, we won't be able to actually see its power. We will be presented with the console
where the app prints information. We will use it to print debug information to validate our
code.
When working on a mobile application we will discuss how to debug the app. This will be
tightly related to the debug options located in the Debug panel. We will get to this part
once we have created a regular app, and we want to improve it.

[ 38 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The Utilities panel (located to the right)
The Utilities panel gives us extra options to configure each active element. At the bottom
part, we have sections with various templates which we can use in our development
process.
At the top, there are two tabs. The first one is called File inspector. It's denoted with an icon
like a new blank page. This tab shows information about the selected file. You can find
information where the file is located on the hard drive and a few other options, as shown
here:

We see the file location of the playground project. Also, it's using iOS as a platform and we
can change that by picking another platform from the list. We can enable text markup in the
playground or disable it. The markup will be discussed later in this chapter.

[ 39 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

The second tab is called Quick Help Inspector. It provides extra contextual information
based on the last, focused item in the editor. It's really handy when using a public interface
(API) from Apple or any other third-party well-written (documented) library. We will learn
more about external libraries and how to use them later in this book.
The number of tabs is more than two, when the project is a regular mobile app. Don't feel
that we are skipping them; we will discuss them when they appear.
At the bottom of the Utilities panel, there is another section, which contains several tabs.
This part contains different templates:
The first is the File Template Library, which can be used to add different files to
a project
The next is the Code Snippet Library, which contains different code snippets
After that is the Object Library, a collection of objects which can be added to a
storyboard
Finally, there is the Media Library, a list of all media items, which are part of
your project or workspace
These panels are there to save you time when looking for something in your project. There
is a neat filter function at the very bottom. Here is a screenshot that shows you how to get
access to a list of all Swift code templates:

[ 40 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

There is a small icon to the left of the filter text field. It switches between a list and grid
view of the template tabs:

Next, we discuss the preferences of the IDE, so we can match our personal preferences.

Xcode preferences window
In this section, we present the preferences window briefly. If we open it, we can see several
tabs, each containing different options about the Xcode:

[ 41 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Let's describe each tab, its role, and what you can find in it.
General: Contains settings about the general build behavior of the Xcode.
Accounts: The tab where the user can link different Apple accounts and source
code repositories. The settings can store the username and password, so the
Xcode can do some actions on the user's behalf.
Behavior: Here, each step/action done by Xcode can display a notification or
even play a specific sound. It's possible to trigger a script or speak the phase
name.

[ 42 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Navigation: Configures where the new code should be opened, once the user
clicks on a source file using the modifier keys such as cmd, Option, Shift.
Fonts & Colors: The Xcode can look different; it's up to you:

Text Editing: A place where you can customize the behavior of the editor.
Key Bindings: If you are a fan of keyboard shortcuts, then this is the place to
customize Xcode. You could become a master if you add some extra shortcuts or
make some predefined ones to fit your needs.
Source Control: Configure the general behavior of the source control integration.
Components: This is the place where you can download an old version of the
simulator.

[ 43 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

In general, you will be able to download simulators which are supporting
specific versions. For example, the oldest one for Xcode 9.3 is iOS 8.1.

Locations: Configure which folders should be used by Xcode for temporary files.
You can change the version of the Command Line Tools, which can be used
from the Terminal window.
Server & Bots: This is a special tab where you can configure the Xcode to
continually build and test your apps.
We aren't new to Xcode anymore, so now is the time to dive into details, such as what's a
playground and how we can use playgrounds to do experiments with Swift.

Playground
Before diving into a mobile project, we will start with a special type of project that will help
us master the Swift language. These projects are a cool place to experiment, without the
extra hassle of setting up a real mobile project. We can experiment with real mobile
functions, without even working on a full mobile project. Playground projects are a really
nice place to prototype algorithms or UI, and simply to have small building blocks, ready
and fully tested, before plugging them into a mobile app.

What is a playground?
Straight from the file generated by Xcode:
"Playground a noun: a place where people can play."
Playground is a simple project, which can be used to practice, experiment, prototype and
play with code and the underlying OS. It's easy to write some code to sketch an idea or to
clarify a concept. The best thing is that you can mix text (markup) with code. Also, it's
possible to use the native functions that are specific for the platform (for example iOS). This
makes playground projects very expressive and realistic.

[ 44 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Let's create a playground and dive deeper into it:
1.
2.
3.
4.
5.
6.
7.

Open Xcode
Select File | New | Playground or simply press "Option + cmd + Shift + N"
Pick a nice namebfor example 4XJGUCZFYBNQMFT
Set the platform to iOS
Click Next
Select a place to save the file
Press Create

As a result of these steps, you will have a new playground, which will only have a few
rows.
The playground can contain more than one page.

In our example, we are using just a single-page playground, but if you want to express
something complex, you can add another page using the + button in the Navigator panel (at
the very bottom).

Let's add some code
Let's get our hands dirty with some code. We can try using the template panel to
implement a switch statement and a GPS loop. How do we do this?
1. Let's open the Utilities panel. To do so, use the topmost right icon on the toolbar
or simply press Option + cmd + 1.
2. Then select the second tab in the bottom part {} to open the code snippets library.
3. Next, type the following in the filter fieldb4XJGUTXJUDI.
4. You should see just a single item.
5. Drag that item to the editor:

[ 45 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

6. Once you drop it, you will see the switch structure with a few placeholders to fill
in.
7. Try to fill the gaps, so the switch looks something like this:
TXJUDITUS\
DBTFTXJGU
QSJOU )FMMP4XJGU
EFGBVMU
QSJOU 8IPBSFZPV
^

8. Then, we can open the console at the bottom to see the output of our program.
Use the
button to open the Debug console where all print messages are
displayed or press cmd + Shift + Y.
9. You should see: Who are you?

[ 46 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Now, let's try to create a GPSJO loop, which prints all numbers from one up to five
inclusive. Let's use the same procedure as before, but at step 3 we should use 4XJGU
GPS for filtering. Then, at step 7 we should try to reach the following:
GPSJJO\
QSJOU = J 
^

It's normal while you are writing code to see some warnings or even errors. Playgrounds
are built automatically on every change in the code, thus, the compiler is showing errors
when the code is not valid. When you are ready, all errors should be gone and in the output
of the program, you will see all numbers from one to five.
To switch to manual mode, press the Play button at the bottom menu and
hold for a bit. A menu with two options should pop upbAutomatically
Run and Manually Run. The first one is selected, but you can switch to
manual mode.
If you are in Manually Run, once you change the code of the playground,
you will have to Run the playground to reflect the changes. A simple save
action is not enough, compared to the Automatically Run mode.
When you start a manual build (or an automatic one was executed), the toolbar at the top
changes briefly. The progress indicator appears while the execution takes place.

[ 47 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

If there is an output of the playground, it is printed on the console. But this is not the only
way to see the evaluation of the code. There is a right panel in the editor, which is really
handy when exploring the playgrounds. Unfortunately, it's not expanded by default, but it
shows the evaluation of each statement. You can resize it with your mouse to make it
visible. Just grab the leftmost edge of the gray panel to the right of the editorbit's easily
distinguishable:

[ 48 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Here is the expanded version of the panel, which shows the value of each line. It looks nice,
when you have just a single statement on each row:

This is not the case when there are two or more statements separated with  .
Keep the code clean and simple by adding just a single statement on each
line. This will help you to write understandable and easily maintainable
code.

[ 49 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Now let's explain the default screen. There are two icons which you see on the line which is
hovered. The first one is Quick Look, which shows the evaluation in a pop-up window.
The other button is Show results. When it's activated, the results are displayed inline. (To
activate this, you can use Editor | Show Result for Current Line):

Different values are presented in a different fashion such as a chart, a list
of values, or simply the last value stored in that variable.

[ 50 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Here is an example, which shows how the value stored in the TVN variable is growing over
time. With the mouse, you can explore the exact value at every single moment:

You can explore the result with the mouse. It's pretty easy to resize the answer area too; just
move the mouse close to the edges, until the pointer changes to a double-headed arrow.
If you want to change the way a result is presented, then use the following option, but it
should be selected first: Editor | Result Display Mode; then three options will be
presented:
Latest Value: Displays the last value of the statement
Value History: Displays a list of all values
Graph: Plots the values
We can see the whole sequence of the invocation in the console (cmd +
Shift + Y).

Playgrounds can contain a lot of code. But there is a neat way to add it to a project by using
auxiliary files.

[ 51 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

How to add auxiliary code to a playground
Each playground may need a bunch of classes which are helping to illustrate the problem
or a solution. There is a handy way to add a chunk of code, which is compiled once it is
added or changed. This means that those parts won't be compiled each time the
playground is executed. The files containing code are called auxiliary files. To add such a
file, we should do the following:
1.
2.
3.
4.
5.
6.

Open the Navigator panel (cmd + 1).
Select the Sources folder.
Press the + button at the bottom of the Navigator panel.
Select New File.
Give the new file a nice name related to its role.
Add the code which you want to reuse in the playground. Don't forget to add
the QVCMJDscope modifier to make it visible in your playground
7. Try to use it in the main playground:

Playgrounds can contain different resources such as images, statistic data, sound, and so
on. These are placed in the 3FTPVSDFT folder. Here is a step-by-step guide on how to add a
resource (image/asset) to a playground.

How to add resource to a playground
Follow these steps to add an image to your playground. Try to use a QOH or KQHbimages
look great once you load them in a playground:
1. Open the Navigator panel (cmd + 1)
2. Select the 3FTPVSDFT folder
3. Press the + button at the bottom of the Navigator panel

[ 52 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

4. Select Add Files to 'Resources'...
5. The file is automatically copied to the 3FTPVSDFT folder
6. Try to use it in the main playground
For example, to use an image in the iOS playground you can use the following code:
MFUJNH6**NBHF OBNFEPQFO@YDPEFQOH

Where the name of the file is PQFO@YDPEFQOH. Don't worry about the code and what
6**NBHF means. We will understand this a bit later on in the book. Take a look at the
following screenshot:

#FFKPICPKOCIGVQ[QWTRNC[ITQWPF

Converting a playground to a workspace
If you want to add a custom framework (external library of code) to your playground, you
have to convert the playground to a workspace. This can be done using File | Save As
Workspace....

[ 53 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Just pick a new name and save the file. Xcode will switch to advanced mode and you will
see a lot of options available. We will discuss how to add third-party libraries to a
workspace later in the book. But it's good to know that you can use playgrounds to test
your framework without any problem.
So far, we know the basics of the playground. Now let's introduce the markup language
and an easy way to make your playgrounds outstanding.

Markup in playgrounds
The playground supports an easy way to write documentation for your code. It's like
comments, which we are familiar with, but the Xcode renders them nicely. Let's do it stepby-step:
1.
2.
3.
4.
5.

Open a playground project
Open the Utilities project
Select the File Inspector
Mark the option Render Documentation
You should see that 1MBZHSPVOEOPVOBQMBDFXIFSFQFPQMF
DBOQMBZ is converted to a good-looking text

Different items in the markup language
First, let's clear up what a markup language is; it is an easy way to write styled text, which
will be rendered using a set of rules. The final result is nicely formatted text.
Here is a code that creates markup (in a playground):
 
)FBEFS#JH
)FBEFS/PSNBM
)FBEFS4NBMM
-JTU
 PQUJPO
 PQUJPO
 PQUJPO
PQUJPO
5IJTJT@JUBMJD@UFYU
5IJTJT@@CPME@@UFYU
5IJTJT@@@CPMEJUBMJD@@@UFYU
5IJTJT CPME UFYU
"DPEFAAAMFUYAAAIBTEJGGFSFOUTUZMF

[ 54 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

"OFYBNQMFGPMMPXT
WBSB
WBSCB 
/PUF
:PVDBOMFBSO4XJGU
=
=
1MBZHSPVOETBSFSFBMMZOJDFQMBDFUPMFBSO4XJGU
 

To create nice documentation, we should learn how to use markup. The benefit is that we
can use most of the formatting while writing documentation for each function, which will
be used in the Utilities panel (the Help tab) in Xcode.
Here is what the previous markup looks like once we enable the Render Document mode
(from the Utilities panel):

[ 55 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

To start new markup section in a playground, you should write the following instead of a
typical comment block:
ZPVSOFXSJDIEPDVNFOUBUJPO

You can also write a comment block like this:
 ZPVSDPEFHPFTIFSF 

This will be converted to a markup, if you are using one of the special structures (see the
following). To enable the Render Document, we can do it using Editor | Show Rendered
Markup. An alternative option is to mark the checkbox Render Document in the Utilities
panel on the right.
If Render Documentation is on, then you won't be able to edit the
markup-comments, because they are converted immediately. You have to
switch off the rendering mode. This can be done using Editor | Show
Raw Markup.

Basic markup items
First of all, when writing markup, we need to add titles for different sections. To do that,
we have to add the  symbol in front of the text and it automatically becomes a header text
with a bigger bold font. For example:
)FBEFS#JH

If we keep adding more  in front then we demote the text:

[ 56 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

If we want to use lists in the text, then we should structure it as follows:
-JTU
 PQUJPO
 PQUJPO
 PQUJPO
PQUJPO

With adding an extra offset, we can push the bullets to the right, simulating subsections.
To create enumerated lists, you should start each option with  like this:
&OVNFSBUFEMJTU
PQUJPO
PQUJPO
PQUJPO

Here is the result of both lists when they are rendered:

When describing some functions or classes, we want to stress some properties. To do that,
we can change the font style easily. Here is how we can write in bold, italics, or mixed:
5IJTJT@JUBMJD@UFYU
5IJTJT@@CPME@@UFYU
5IJTJT@@@CPMEJUBMJD@@@UFYU
5IJTJT CPME UFYU

[ 57 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

Here is how this text is rendered:

Sometimes, we want to quote a variable or a short code snippet. It's really nice if we can
distinguish it easily from the rest of the text. This can be achieved by surrounding the text
in Abthe ascent symbol.
Here is an example:
5IFDPEFAMFUYAIBTEJGGFSFOUTUZMF

If you want to add an example block, then simply add an empty line, to separate the block
and add in an extra offset:
FNQUZMJOF
WBSB
WBSCB 

The preceding code creates this:

Sometimes, images are really important; here is the easiest way to show an image:
<*NBHFGSPNSFTPVSDFT> PQFO@YDPEFQOH

[ 58 ]

Getting Familiar with Xcode and Playgrounds

Chapter 2

If you need to add some links here, this is how you can do it:
<5FYU> 63<4XJGU> IUUQTTXJGUPSH

Finally, if you want to add a note to explain something important in a playground, you can
use the following code:
/PUF
:PVDBOMFBSO4XJGU
=
=
1MBZHSPVOETBSFBSFBMMZOJDFQMBDFUPMFBSO4XJGU

The rendered note looks slick and can be used to outline something really important:

We have presented some popular markup formatted text, which will add a final touch to
your documentation. Some of the styling could be used to improve your documentation,
which is rendered in the Utilities panel.

Summary
In this chapter, we learned how to install the Xcode app and how to use it in general. We
are familiar with the basic components of the IDE and we have created our first
playground. It was pretty basic, but we know how to write Swift code, which is
automatically evaluated. We can read the errors and we can try to resolve them.
The next chapter will teach us how to create our first mobile app. It will explain the
structure of a mobile project and how to start adding simple features to it. Let's dive deep
into iOS and produce something which can be executed on mobile devices.

[ 59 ]

3
Creating a Minimal Mobile App
In this chapter, we are going to develop our first mobile app using Xcode and our basic
Swift knowledge. We will get familiar with the basic organization of an iOS project. We will
run it in a simulator, which will be our first friend through the development process. A Git
version control system will be introduced, because it's part of Xcode. With it, through the
development process, we can track our changes to the source code. Then, at some point, we
can easily switch back to a specific version. We will learn how to keep our code under
control and to jump to a specific version, developed earlier by us.
In this chapter, we will cover the following topics:
Developing our first mobile app using Xcode
Git

Creating a Minimal Mobile App

Chapter 3

Your first iOS application
Let's start with creating your first iOS mobile project using Xcode. Here are the steps that
will guide you through the process.
1. Go ahead and start Xcode. If you start Xcode for the first time or there is no active
project opened, then you will see the following screen (please check $IBQUFS
, Getting Familiar with Xcode and Playgrounds, if you don't have Xcode already
installed on your Mac):

2. Click on Create a new Xcode project. If you have an opened project, then simply
use the menu at the top to create a new project by navigating to File | New |
Project (shift + cmd + N):

[ 61 ]

Creating a Minimal Mobile App

Chapter 3

3. Select the iOS tab at the top.
This book is focused on iOS development, but, in general, there is no huge
difference between all other platformsbmacOS, watchOS, or tvOS. They
have different capabilities, but they can run apps developed in Swift.
4. Then select Single View Application.
This is a special type of application, which consists of a single-view
controller which presents a single view.

Xcode will generate an empty starting project, based on the selected template,
which has just a single view. The project is not empty, it contains the very basic
building blocks. Don't worry; we will learn how to add extra views and improve
the project's structure.

[ 62 ]

Creating a Minimal Mobile App

Chapter 3

Here are all the other types of projects that are available in the current Xcode
version:
Application projects: These are mobile applications which present data to the
user.
Game: You should pick this project template if you want to
develop a game for iOS.
Augmented reality app: A project template that boots the
augmented reality scene setup. We will be working on a limited
number of iOS devicesbthe ones which support AR.
Document based app: A special template that easily enables
document manipulation on the device and in the cloud.
Master-detail application: A special project template, which is a
good start if you want to display data in a table/list. The project
could be universal (for iPad and iPhone), or for iPhone only, or for
iPad only.
Page-based application: A special template, which displays a set
of views (pages). There is a nice way to navigate between them.
Tabbed application: An application template, which has a tab bar
control (a menu of several items at the bottom) that can be used to
switch between different sections in the app. This is quite a
popular template because many apps which present data in
sections use this neat approach.
Sticker pack application: This template project is an extension of
the iMessage app, which is part of the iOS, which will define new
Stickers that can be used in the app. It's something new starting
from iOS 10.
iMessage application: A template project which helps you develop
an iMessage app integration. This special type of project is used
when you want to provide a seamless integration of your app and
iMessage app.
Framework and library project:
Cocoa Touch framework: A template which helps you to create a
custom framework (a set of classes and resources, larger than a
library) that can be shared across several iOS projects. There is a
chapter later in which we will learn how to integrate open source
frameworks within our iOS project(s).

[ 63 ]

Creating a Minimal Mobile App

Chapter 3

Cocoa Touch static library: A project template which should be
used when you want to define a separate set of classes, resources
and assets, which can be distributed separately and reused in
different iOS projects. Compared to the previous framework
project, the static library is much more specific. In general, several
libraries can form a framework, but sometimes it's just a single one.
The distribution of static libraries is harder, compared to the
distribution of frameworks.
Metal library: A template that should be used in case you want to
deliver a Metal-based framework (for games or Metal-enabled
apps).
5. Click on Next and the following screen will appear.

[ 64 ]

Creating a Minimal Mobile App

Chapter 3

6. On this screen, we should fill in some details, which we can alter later from the
project's settings:
Product Name: This is the name of the app. We can use .Z'JSTU
J04BQQ.
Team: Leave that as None for now. Here, you can pick on behalf of
which team you are going to develop this app. You may be part of
several teams or accounts in the App Store.
Organization Name: This is the name of the company that is the
owner of the app. You can enter arbitrary text here.
Organization Identifier: The bundle identifier prefix of your
organization. Usually, people use the domain of the organization in
reverse order. For example, BQQPTFTUVEJPDPN is converted to
DPNBQQPTFTUVEJP.
Bundle Identifier: This is a read-only field, but it's composed by
appending the organization identifier and the product name (after a
small transformation). For example, if you use DPNNZDPNQBOZ and .Z
'JSTUJ04BQQ the value there will be DPNNZDPNQBOZ.Z'JSTU
J04BQQ.
Language: Keep it as it is; Swift is what we are learning. You may
change it with Objective-C.
Devices: Leave it as Universal. This means that the app will run on
both device families, iPhone and iPad. You can decide to develop it
just for phones or for tablets only, then pick the corresponding value.
Use core data: You can check this if you are planning to use core data
for storing data locally on the device. This won't be discussed in the
book, but you can find about it at IUUQTEFWFMPQFSBQQMFDPN
MJCSBSZDPOUFOUEPDVNFOUBUJPO%BUB.BOBHFNFOU%FWQFEJB
$PSF%BUBDPSF%BUB0WFSWJFXIUNM.

Include Unit Test: Xcode will generate a simple test, which could be
used to test some parts of your app. This is great in case you want to
test your code.
Include UI Tests: Leave it selected. Xcode will generate separate
projects with UI tests, which should be developed in case you want to
test the UI of your app.
7. Click on Next.
8. Select a folder where the new project will be saved on the disk. For example, in
the %PDVNFOUT folder, create a new folder called 4XJGUQSPKFDUT. Keep
the Source Control option marked to create a local Git repository, as shown here:

[ 65 ]

Creating a Minimal Mobile App

Chapter 3


You will learn about it later in the chapter.

8. Click on Finish.
Xcode will start generating a bunch of files and will open the project for you:

2TQLGEV

[ 66 ]

Creating a Minimal Mobile App

Chapter 3

You will see the project settings screen. There are two targets: My First iOS app and My
First iOS appUITests. This is in case you have used the proposed name, but these could be
named differently based on the name that you picked for your product earlier.
On this screen, you can change the bundle identifier, in the Identity section at the top. In
the Display Name field, you can specify the name of the app, which will be visible below
the icon of the app on the device. The Version field is used to set a specific version of your
application. Usually, the versioning starts from 1.0.0, but you can use a different
approach. The build number is there to distinguish different builds from the same version.
It should be increased if you upload a different version in the App Store.
In the sign-in section, you have to pick a team. You can pick Add an Account... and if you
have an Apple ID, you can use it. If you haven't, then simply use the Create Apple
ID button and follow the instructions (everything is done in Xcode):

With your personal account, you can run the app on an iOS device.

To run the app on an iOS device, you have to connect it with a USB cable to your computer.
The device will ask you whether you trust this computer (pick Trust) and the device will
appear in the list, next to the target, at the top of Xcode:

[ 67 ]

Creating a Minimal Mobile App

Chapter 3

To pick the device you have to click on iPhone 7 Plus and you will see the following menu,
where you can see your device listed:

The next section is Deployment Info. It is used to specify the device family (keep it as it is).

[ 68 ]

Creating a Minimal Mobile App

Chapter 3

The main interface points to the .BJOTUPSZCPBSE, which we will discuss a bit later in the
chapter. The role of this field is to show the main storyboard. A TUPSZCPBSE is a special
type of file that is used to describe the UI of an application or framework. One application
can have multiple storyboards. It's possible to have applications without storyboards, but
by using them, it's much easier to describe and depict complex UI dependencies.
A device orientation list of checked options defines the supported orientations by the app.
If you want to support only Portrait mode, then you have to deselect the other options. In
the current case, we should deselect Landscape Left and Landscape Right.
The status bar style can be configured next. The default can be replaced with light, which
means that the text color will become white. There are two sub-options: to hide the status
bar completely once the app is started, and to request full-screen mode wherein the app
will be using the whole screen estate.
Most of these settings can be configured programmatically using code, but
it's much easier if we do it through the General panel.

The other sections are for configuring icons and embedding external code in the app. These
will be explained later in the book, so don't bother with them right now.
The rest of the tabs on this screen are:
Capabilities: From here, we can add extra capabilities to our app. For example,
support of maps, background execution, data protection, key-chain sharing,
integration with wireless accessories, and interaction with HealthKit or HomeKit.
If you are using a paid account, then you have access to some more, such as Siri
integration, push notification, iCloud, GameCenter, Wallet, Apple Pay, In-App
Purchase, Personal VPN, and Network Extensions.

[ 69 ]

Creating a Minimal Mobile App

Chapter 3

Not all capabilities are available, if you are using a free personal account.
You have to register for a paid account in the App Store, which costs $99
per year, but this will be needed once you want to use something that is
not part of the free tier. For example, if you want to publish your app in
the App Store, then you have to switch to a paid account.
Resource Tags: This is place where you can categorize different resources, so
they are fetch on the go. It means that not all resources will be downloaded with
your app at the very first moment. Some categories will be fetched later, so the
user can download the app easily. This technique is advanced and it's applicable
for huge apps, which benefit when the user is downloading just part of the
resources. If you need further details you can read them here c IUUQT
EFWFMPQFSBQQMFDPNMJCSBSZDPOUFOUEPDVNFOUBUJPO'JMF.BOBHFNFOU
$PODFQUVBM0O@%FNBOE@3FTPVSDFT@(VJEFJOEFYIUNM

Info: This tab presents application information. The same information can be
found if you open the *OGPQMJTU file (cmd + shift + O and then type
*OGPQMJTU).
Build Settings: This tab contains advanced options of the compiler and your
application. To see all the settings, you have to select All (it's next to Basic and
Customized):

Use the search box on the right to find what you need. There are too many
options to be tweaked, so don't waste time; simply filter.

Build Phases: On this screen, all phases performed while building the project are
listed. You can add extra ones or remove one of thesecplease, don't remove any!

[ 70 ]

Creating a Minimal Mobile App

Chapter 3

A really important part is Compile Sources. You can explore the list of files,
which should be compiled:

The other key phase is Copy Bundle Resources. Xcode is copying the resources
which describe the UI of our app.
Build Rules: This last tab contains all default rules which are executed by Xcode.
You can add custom rules which can transform your source code. For the
default tasks, Xcode already has a set of default rules.

We learned a bit more about the project settings and how to change those. This is the time
to start our app in the simulator. Please pick the type of simulator which should be used;
it's located next to the target (at the very top of the Xcode). It should say iPhone 7 Plus, for
example. Then, click on the big Play button to run the project. You should see a Build
Succeeded message fading in and out at the bottom of your screen.

[ 71 ]

Creating a Minimal Mobile App

Chapter 3

The simulator will be started automatically. You should see something similar to this:

Yeah, that's right: the app running on the screen is blank. Next, we will understand more
about the project organization and, in the next chapter, we will start adding new things to
it.
The simulator is a separate application, which simulates an iOS device. It could simulate on
an iPad. You have a separate menu to control it. You can do a lot of actions, which the real
device can do.
For example you can do the following:
Take screenshots
Rotate the simulator to the left (cmd + left arrow)
Rotate the simulator to the right (cmd + right arrow)
Shake gestures (ctrl + cmd + Z)
Go to the home screen (cmd + shift + H)
Activate Siri (alt + shift + cmd + H)
Reboot the device
Simulate TouchID
Simulate memory warning

[ 72 ]

Creating a Minimal Mobile App

Chapter 3

Simulate call
Toggle hardware keyboard
Simulate force touch
Simulate external display
Send fake locations
Open System log
Trigger iCould sync
These are the most popular ones and they can be found in the menu. Feel free to explore
them and don't forget that this is similar to a regular phone. So, you have settings and you
can configure your device.
You can copy images from the filesystem by simply dragging and
dropping those on top of the simulator. The images will appear in the
photos app.
Not all apps, which are part of real iOS devices, such as App Store,
Camera, Notes, and others, are part of the simulator.
Now is the time to explore the project structure. Let's take a look at the Navigator panel on
the left. (You can open it using View | Navigators | Show Project Navigator or cmd +
1 (see more in $IBQUFS, Getting Familiar with Xcode and Playgrounds):

[ 73 ]

Creating a Minimal Mobile App

Chapter 3

Project structure
At the top, we see the project's icon My First iOS app and its internal structure.
The first is the My First iOS app group (folder in this case).
It's up to you to create a corresponding folder on the filesystem. The
project structure may match the file structure, but it could be different.

The yellow folders are called groups and we see three groups in the Navigator.
Dragging files to different groups doesn't affect the real file on the
filesystem.

Let's describe each file in the main group, named after our project:
"QQ%FMFHBUFTXJGU
7JFX$POUSPMMFSTXJGU
.BJOTUPSZCPBSE
"TTFUTYDBTTFUT
-BVODI4DSFFOTUPSZCPBSE
*OGPQMJTU

We will start with "QQ%FMFHBUFTXJGU, which manages the interactions between the app
and the underlying OS.

AppDelegate
The delegate pattern is used to delegate some responsibilities to another class. It's b