Table Of ContentLearning Swift
Second Edition
Develop the skills required to create compelling,
maintainable, and robust iOS and OS X apps with Swift
Andrew J Wagner
BIRMINGHAM - MUMBAI
Learning Swift
Second Edition
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2015
Second edition: March 2016
Production reference: 1170316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-751-2
www.packtpub.com
Credits
Author Project Coordinator
Andrew J Wagner Izzat Contractor
Reviewer Proofreader
Guan Gui Safis Editing
Commissioning Editor Indexer
Kartikey Pandey Hemangini Bari
Acquisition Editors Production Coordinator
Vivek Anantharaman Shantanu N. Zagade
Chaitanya Nair
Cover Work
Shantanu N. Zagade
Content Development Editor
Viranchi Shetty
Technical Editor
Saurabh Malhotra
Copy Editors
Kevin McGowan
Sneha Singh
About the Author
Andrew J Wagner is a software developer who concentrates on iOS development
and backend web services. He has a degree in computer engineering from Rensselaer
Polytechnic Institute, New York. Currently, he works for a development shop named
Chronos Interactive based in Denver, CO. He has experience of working with and
for large-scale and small-scale companies, as well as running his own contracting
and app companies. He is passionate about using computers as a creative outlet and
writing software that is beautiful in implementation, functionality, and experience.
When he isn't working or spending time with friends and family, he writes for his
blog at http://drewag.me.
I would like to thank my friends and family for being there for
me as support for both my troubles and triumphs. Without their
encouragement, I would not have finished this book or achieved any
of the other things in my life that make me proud. An especially big
thanks to my parents, Fern and Joe, for continually providing me
with the tools I need to do the things I love.
About the Reviewer
Guan Gui graduated from the University of Melbourne. He implemented the first
system of its kind for beekeepers using satellite sensory data to help them deploy
their honeybees better. He is also a big fan of Apple. He started his own open source
project—Uni Call (unicall.guiguan.net) for OS X. While his research focus is on
machine learning, he enjoys the more practical side of CS: developing apps using
Swift and JavaScript. Currently, he is trying to set his own start-up. Big ideas to
change the world always spin in his head!
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at customercare@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
Table of Contents
Preface ix
Chapter 1: Introducing Swift 1
Defining our goals for this book 1
Setting up the development environment 3
Running our first swift code 3
Understanding playgrounds 7
Learning with this book 8
Summary 9
Chapter 2: Building Blocks – Variables, Collections,
and Flow Control 11
Core Swift types 12
Constants and variables 12
Containers 12
Tuples 13
Arrays 13
Dictionaries 14
Swift's type system 15
Printing to the console 17
Control flow 18
Conditionals 18
Switches 19
Loops 22
Functions 25
Basic functions 25
Parameterized functions 26
Functions that return values 27
Functions with default arguments 29
Guard statement 30
[ i ]
Table of Contents
Bringing it all together 31
Summary 37
Chapter 3: One Piece at a Time – Types, Scopes, and Projects 39
Structs 40
Types versus instances 40
Properties 41
Member and static methods 42
Computed properties 45
Reacting to property changes 46
Subscripts 47
Custom initialization 48
Classes 51
Inheriting from another class 51
Initialization 53
Overriding initializer 54
Required initializer 54
Designated and convenience initializers 56
Overriding methods and computed properties 57
Methods 57
Computed properties 58
Casting 59
Upcasting 60
Downcasting 60
Enumerations 61
Basic declaration 61
Testing enumeration values 62
Raw values 63
Associated values 64
Methods and properties 66
Projects 67
Setting up a command-line Xcode project 68
Creating and using an external file 70
Interfacing with code from other files 71
File organization and navigation 74
Extensions 75
Scope 76
How scope is defined 76
Nested types 76
Access control 77
Summary 78
[ ii ]
Table of Contents
Chapter 4: To Be or Not To Be – Optionals 81
Defining an optional 82
Unwrapping an optional 83
Optional binding 83
Forced unwrapping 85
Nil coalescing 87
Optional chaining 87
Implicitly unwrapped optionals 89
Debugging optionals 91
The underlying implementation 94
Summary 95
Chapter 5: A Modern Paradigm – Closures
and Functional Programming 97
Functional programming philosophy 98
State and side effects 98
Declarative versus imperative code 99
Closures 101
Closures as variables 101
Closures as parameters 102
Syntactic sugar 103
Building blocks of functional programming in Swift 104
Filter 105
Reduce 105
Map 107
Sort 107
How these affect the state and nature of code 108
Lazy evaluation 108
Example 109
Summary 112
Chapter 6: Make Swift Work For You – Protocols and Generics 113
Protocols 113
Defining a protocol 114
Implementing a protocol 114
Using type aliases 117
Generics 119
Generic function 119
Generic type 120
[ iii ]