Table Of ContentSwift Apprentice
Swift Apprentice: Fourth Edition
Ehab Amer, Alexis Gallagher, Matt Galloway, Eli Ganim, Ben Morrow, Cosmin Pupăză
and Steven Van Impe
Copyright ©2018 Razeware LLC.
Notice of Rights
All rights reserved. No part of this book or corresponding materials (such as text,
images, or source code) may be reproduced or distributed by any means without prior
written permission of the copyright owner.
Notice of Liability
This book and all corresponding materials (such as source code) are provided on an “as
is” basis, without warranty of any kind, express of implied, including but not limited to
the warranties of merchantability, fitness for a particular purpose, and
noninfringement. In no event shall the authors or copyright holders be liable for any
claim, damages or other liability, whether in action of contract, tort or otherwise,
arising from, out of or in connection with the software or the use of other dealing in the
software.
Trademarks
All trademarks and registered trademarks appearing in this book are the property of
their own respective owners.
raywenderlich.com 2
Swift Apprentice
Dedications
"Thanks to my family for their unconditional support, and my
beautiful Merche for being a wonderful blessing."
— Ehab Amer
"To my wife and kids -- Ringae, Odysseus, and Kallisto."
— Alexis Gallagher
"To my amazing family who keep putting up with me spending my
spare hours writing books like this."
— Matt Galloway
"To my loved ones: Moriah, Lia and Ari."
— Eli Ganim
"For MawMaw. A talented cook, a loving smooch, a worthy opponent
in chicken foot; a home weaver. Her blessing abides beyond her
time."
— Ben Morrow
"To my awesome girlfriend Oana and my cute dogs Sclip and Nori for
believing in me all the way."
— Cosmin Pupăză
raywenderlich.com 3
Swift Apprentice
About the Authors
Ehab Amer is an author of this book. He is a very enthusiastic Lead
iOS developer with a very diverse experience, from building games to
enterprise applications and POCs, especially when exploring new
technologies. In his spare time, TV shows take the majority, followed
by video games. When away from the screen, he goes with his friends
for escape room experiences or to explore the underwater world
through diving.
Alexis Gallagher is an author of this book. He is the Chief
Technology Officer of Topology Eyewear, a San Francisco startup,
which creates the most Swifty and the most bespoke glasses in the
world, right on your iPhone, using a heady cocktail of machine
learning, augmented reality, manufacturing robots and lasers. He
relishes taking the time to reconsider the fundamentals, in design,
engineering and life. He lives in his hometown of San Francisco with
his wife and kids.
Matt Galloway is an author of this book. He is a software engineer
with a passion for excellence. He stumbled into iOS programming
when it first was a thing, and he has never looked back. When not
coding, he likes to brew his own beer.
Eli Ganim is an author of this book. He is an engineering manager at
Facebook. He is passionate about teaching, writing and sharing his
knowledge with others.
Ben Morrow is an author of this book. He delights in discovering the
unspoken nature of the world. He’ll tell you the surprising bits while
on a walk. He produces beauty by drawing out the raw wisdom that
exists within each of us.
raywenderlich.com 4
Swift Apprentice
Cosmin Pupăză is an author of this book. He is a tutorial writer from
Romania. He has worked with more than a dozen programming
languages over the years, but none has made such a great impact on
himself as Swift. When not coding, he either plays the guitar or
studies WWII history.
About the Editors
Steven Van Impe is the author of the challenges of this book and
also the technical editor of this book. Steven is a computer science
lecturer at the University College of Ghent, Belgium. When he’s not
teaching, Steven can be found on his bike, rattling over cobblestones
and sweating up hills, or relaxing around the table, enjoying board
games with friends. You can find Steven on Twitter as @svanimpe.
Wendy Lincoln is an editor of this book. She is driven by an
insatiable curiosity about technology, and as a result she manages
technical projects, does technical editing, and squanders her spare
time learning about tech. When she’s not geeking out, you’ll find her
in the waves or doing home-improvement projects with her husband.
Ray Fix is the final pass editor of this book. A passionate Swift
educator, enthusiast and advocate, he is actively using Swift to create
Revolve--the next generation in research microscopy at Discover Echo
Inc. He serves as the iOS tutorials topics master at
RayWenderlich.com. Ray is mostly-fluent in spoken and written
Japanese and stays healthy by walking, jogging, and playing ultimate
frisbee. When he is not doing one of those things, he is writing and
dreaming of code in Swift.
About the Artist
Vicki Wenderlich is the designer and artist of the cover of this book.
She is Ray’s wife and business partner. She is a digital artist who
creates illustrations, game art and a lot of other art or design work for
the tutorials and books on raywenderlich.com. When she’s not
making art, she loves hiking, a good glass of wine and attempting to
create the perfect cheese plate.
raywenderlich.com 5
Swift Apprentice
Table of Contents: Overview
Introduction ............................................................................. 16
Section I: Swift Basics........................................................... 22
Chapter 1: Expressions, Variables & Constants 24
Chapter 2: Types & Operations................................ 51
Chapter 3: Basic Control Flow ................................. 68
Chapter 4: Advanced Control Flow........................ 84
Chapter 5: Functions.................................................... 98
Chapter 6: Optionals ................................................. 112
Section II: Collection Types ............................................. 124
Chapter 7: Arrays, Dictionaries & Sets............... 126
Chapter 8: Collection Iteration with Closures 149
Chapter 9: Strings....................................................... 161
Section III: Building Your Own Types........................... 176
Chapter 10: Structures............................................. 178
Chapter 11: Properties............................................. 190
Chapter 12: Methods ................................................ 203
Chapter 13: Classes ................................................... 217
Chapter 14: Advanced Classes.............................. 231
Chapter 15: Enumerations...................................... 252
raywenderlich.com 6
Swift Apprentice
Chapter 16: Protocols............................................... 268
Chapter 17: Generics ................................................ 285
Section IV: Advanced Topics ........................................... 298
Chapter 18: Access Control & Code
Organization................................................................. 299
Chapter 19: Custom Operators, Subscripts &
Keypaths......................................................................... 315
Chapter 20: Pattern Matching............................... 329
Chapter 21: Error Handling.................................... 348
Chapter 22: Encoding & Decoding Types.......... 364
Chapter 23: Asynchronous Closures &
Memory Management .............................................. 373
Chapter 24: Value Types & Value Semantics.... 387
Chapter 25: Protocol-Oriented Programming 403
Conclusion.............................................................................. 417
More Books You Might Enjoy ......................................... 418
raywenderlich.com 7
Swift Apprentice
Table of Contents: Extended
Introduction ............................................................................. 16
Who this book is for.......................................................................................................... 17
What you need.................................................................................................................... 17
How to use this book........................................................................................................ 17
What's in store.................................................................................................................... 18
Book source code and forums...................................................................................... 19
Book updates....................................................................................................................... 19
License.................................................................................................................................... 19
Acknowledgments............................................................................................................. 20
About the cover.................................................................................................................. 21
Section I: Swift Basics........................................................... 22
Chapter 1: Expressions, Variables & Constants......... 24
How a computer works................................................................................................... 24
Playgrounds......................................................................................................................... 31
Getting started with Swift.............................................................................................. 35
Printing out.......................................................................................................................... 36
Arithmetic operations...................................................................................................... 37
Math functions.................................................................................................................... 42
Naming data......................................................................................................................... 43
Increment and decrement.............................................................................................. 47
Key points............................................................................................................................. 48
Challenges............................................................................................................................ 49
Chapter 2: Types & Operations ........................................ 51
Type conversion.................................................................................................................. 51
Strings..................................................................................................................................... 55
Strings in Swift.................................................................................................................... 58
Tuples...................................................................................................................................... 61
A whole lot of number types......................................................................................... 63
A peek behind the curtains: Protocols...................................................................... 64
raywenderlich.com 8
Swift Apprentice
Key points............................................................................................................................. 65
Challenges............................................................................................................................ 66
Chapter 3: Basic Control Flow.......................................... 68
Comparison operators..................................................................................................... 68
The if statement................................................................................................................. 73
Loops....................................................................................................................................... 78
Key points............................................................................................................................. 81
Challenges............................................................................................................................ 82
Chapter 4: Advanced Control Flow ................................ 84
Countable ranges............................................................................................................... 84
For loops................................................................................................................................ 85
Switch statements............................................................................................................. 91
Key points............................................................................................................................. 96
Challenges............................................................................................................................ 97
Chapter 5: Functions............................................................. 98
Function basics................................................................................................................... 98
Functions as variables................................................................................................... 105
Key points........................................................................................................................... 108
Challenges.......................................................................................................................... 109
Chapter 6: Optionals.......................................................... 112
Introducing nil.................................................................................................................. 112
Introducing optionals.................................................................................................... 114
Unwrapping optionals................................................................................................... 116
Introducing guard........................................................................................................... 119
Nil coalescing.................................................................................................................... 121
Key points........................................................................................................................... 122
Challenges.......................................................................................................................... 122
Section II: Collection Types ............................................. 124
Chapter 7: Arrays, Dictionaries & Sets ....................... 126
Mutable versus immutable collections.................................................................. 126
raywenderlich.com 9
Swift Apprentice
Arrays................................................................................................................................... 126
What is an array?............................................................................................................. 127
When are arrays useful?............................................................................................... 127
Creating arrays................................................................................................................ 127
Accessing elements........................................................................................................ 128
Modifying arrays............................................................................................................. 132
Iterating through an array........................................................................................... 135
Running time for array operations........................................................................... 136
Dictionaries....................................................................................................................... 137
Creating dictionaries..................................................................................................... 138
Accessing values.............................................................................................................. 139
Modifying dictionaries.................................................................................................. 140
Sets....................................................................................................................................... 143
Key points........................................................................................................................... 145
Challenges.......................................................................................................................... 145
Chapter 8: Collection Iteration with Closures......... 149
Closure basics................................................................................................................... 149
Custom sorting with closures.................................................................................... 154
Iterating over collections with closures................................................................. 154
Key points........................................................................................................................... 159
Challenges.......................................................................................................................... 159
Chapter 9: Strings................................................................ 161
Strings as collections..................................................................................................... 161
Strings as bi-directional collections......................................................................... 166
Substrings........................................................................................................................... 167
Encoding............................................................................................................................. 168
Key points........................................................................................................................... 173
Challenges.......................................................................................................................... 174
Section III: Building Your Own Types........................... 176
Chapter 10: Structures ..................................................... 178
Introducing structures.................................................................................................. 179
raywenderlich.com 10