Learning Swift: Building Apps For macOS, iOS, and Beyond 2nd Edition Paris Buttfield-Addison Download
Learning Swift: Building Apps For macOS, iOS, and Beyond 2nd Edition Paris Buttfield-Addison Download
DOWNLOAD EBOOK
Learning Swift: Building Apps for macOS, iOS, and Beyond 2nd
Edition Paris Buttfield-Addison pdf download
Available Formats
Learning Swift Building Apps for OSX, iOS, and Beyond Jon
Manning
d Sw
Ed if t
iti 3.x
on
Learning
Swift
BUILDING APPS FOR macOS, iOS, AND BEYOND
Jonathon Manning,
Paris Buttfield-Addison & Tim Nugent
Learning Swift
Building Apps for macOS, iOS, and Beyond
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Swift, the cover image, and
related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the authors have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-96706-5
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
iii
Working with Strings 42
Comparing Strings 43
Searching Strings 43
Optional Types 44
Type Casting 46
Tuples 47
Arrays 47
Dictionaries 49
Enumerations 50
Associated Values 51
Sets 52
Functions and Closures 53
Using Functions as Variables 56
Closures 58
The defer Keyword 59
The guard Keyword 60
Making Your Code Swifty 60
Conclusion 61
iv | Table of Contents
Structuring an App 92
The Application Delegate 93
Window Controllers and View Controllers 93
Nibs and Storyboards 94
Conclusion 94
Table of Contents | v
Part III. An iOS App
7. Setting Up the iOS Notes App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Designing the iOS Notes App 186
Creating the iOS Project 192
Enabling the iOS App for iCloud 196
Defining a Document Type 200
Conclusion 202
vi | Table of Contents
Viewing Attachments 300
Deleting Attachments 310
Conclusion 317
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Welcome to Learning Swift! This book will help you put the Swift programming lan‐
guage into practice by walking you through the development of a note-taking appli‐
cation for the Apple iOS, macOS, and watchOS platforms.
Swift is a pretty amazing modern language, taking the best from other newer lan‐
guages without reinventing the wheel. Swift is easy to write, easy to read, and really
hard to make mistakes in.
Our philosophy is that the best way to learn Swift is to build apps using it! To build
apps, though, you need a great framework, and Apple has several: Cocoa, Cocoa
Touch, and WatchKit, to name only a few. This book could quite easily be titled
Learning Cocoa and Cocoa Touch with Swift, or something similar, because the frame‐
works are just as important as the language itself. At the time of writing, Swift is cur‐
rently at version 3, and has a bright future ahead of it.
ix
frameworks, through the construction of a complete app for both macOS and iOS. As
a reminder, Swift is the programming language, Cocoa is the framework for macOS
apps, Cocoa Touch is the framework for iOS apps, and somewhat predictably,
watchOS is the framework for the Apple Watch.
This book’s approach differs from that of other programming books that you may
have encountered. As we’ve mentioned, we believe that the best way to learn Swift is
to build apps using it. We assume that you’re a reasonably capable programmer, but
we don’t assume you’ve ever developed for iOS or macOS, or used Swift or Objective-
C before. We also assume that you’re fairly comfortable navigating macOS and iOS as
a user.
x | Preface
Chapter 9 creates an interface on iOS for displaying our notes.
Chapter 10 sets up the iOS app to handle attachments.
Chapter 11 adds image support to the iOS app.
Chapter 12 adds sharing and searching support to the iOS app.
Chapter 13 adds audio, video, and location attachments to the iOS app.
Chapter 14 finishes the iOS app with a whole lot of polish!
In Part IV, “Extending Your Apps”, we add a watchOS app and explore bug hunting
and performance tuning.
Chapter 15 adds a watchOS app to the iOS app, allowing for Apple Watch support.
Chapter 16 explores debugging and performance tuning.
Preface | xi
This element indicates a warning or caution.
O’Reilly Safari
Safari (formerly Safari Books Online) is a membership-based
training and reference platform for enterprise, government,
educators, and individuals.
Members have access to thousands of books, training videos, Learning Paths, interac‐
tive tutorials, and curated playlists from over 250 publishers, including O’Reilly
Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐
sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press,
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe
Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and
Course Technology, among others.
For more information, please visit http://oreilly.com/safari.
xii | Preface
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/learning-swift.
To comment or ask technical questions about this book, send email to bookques‐
[email protected].
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Jon thanks his mother, father, and the rest of his crazily extended family for their tre‐
mendous support.
Paris thanks his mother, without whom he wouldn’t be doing anything nearly as
interesting, let alone writing books.
Tim thanks his parents and family for putting up with his rather lackluster approach
to life.
We’d all like to thank our editors, Rachel Roumeliotis and Brian MacDonald—their
skill and advice were invaluable to completing the book. Likewise, all the O’Reilly
Media staff we’ve interacted with over the course of writing the book have been the
absolute gurus of their fields.
A huge thank you to Tony Gray and the Apple University Consortium (AUC) for the
monumental boost they gave us and others listed on this page. We wouldn’t be writ‐
ing this book if it weren’t for them. And now you’re writing books, too, Tony—sorry
about that!
Preface | xiii
Thanks also to Neal Goldstein, who deserves full credit and/or blame for getting us
into the whole book-writing racket.
We’re thankful for the support of the goons at MacLab (who know who they are and
continue to stand watch for Admiral Dolphin’s inevitable apotheosis), as well as pro‐
fessor Christopher Lueg, Dr. Leonie Ellis, and the rest of the staff at the University of
Tasmania for putting up with us. “Apologies” to Mark Pesce. He knows why.
Additional thanks to Rex S., Nic W., Andrew B., Jess L., and Ash J., for a wide variety
of reasons. And very special thanks to Steve Jobs, without whom this book (and many
others like it) would not have reason to exist.
Thanks also to our tech reviewers, with special thanks to Chris Devers and Tony Gray
for their thoroughness and professionalism.
Finally, thank you very much for buying our book—we appreciate it! And if you have
any feedback, please let us know. You can email us at [email protected] and find us
on Twitter at @thesecretlab.
xiv | Preface
PART I
Swift Basics
CHAPTER 1
Getting Started
This book teaches the Swift 3 programming language by exploring the development
of three applications for Apple platforms: macOS, iOS, and watchOS. This book’s
approach might differ from what you’re used to, because our philosophy is that the
best way to learn Swift is to build apps using it! The vast majority of the code in this
book will be part of the apps we’re building—a full note-taking app for macOS, iOS,
and watchOS—rather than individual pieces of sample code. You can see the final
product in Figure 1-1.
3
Figure 1-1. Our finished app, for macOS, iOS, and watchOS
Our app is fully functional, but we do make some deliberate design and feature deci‐
sions along the way to constrain the scope a little (the book is almost 500 pages!). As
we mentioned in the Preface, we assume that you’re a reasonably capable program‐
mer, but we don’t assume you’ve ever developed for iOS or macOS, or used Swift or
Objective-C before. We also assume that you’re fairly comfortable navigating macOS
and iOS as a user.
Programming with Swift, and using the Cocoa and Cocoa Touch frameworks to
develop macOS and iOS apps, respectively, involves using a set of tools developed by
Apple. In this chapter, you’ll learn about these tools, where to get them, how to use
them, how they work together, and what they can do. At the end of this chapter, you’ll
make a very simple Swift application for iOS. Then we dive into the details of the
Swift language and Apple’s frameworks in the following two chapters.
Swift is open source, but this doesn’t really mean much when it
comes to using it to develop apps for macOS, iOS, and watchOS.
There’s an excellent community of people working on the language
that you can find at the Swift website.
With the introduction of Apple’s curated App Stores for macOS, iOS, and watchOS, as
well as emerging Apple platforms like tvOS, the Developer Program has become the
official way for developers to provide their credentials when submitting applications
to Apple—in essence, it is your ticket to selling apps through Apple. In this chapter,
you’ll learn how to sign up for the Apple Developer Program, as well as how to use
Xcode, the development tool used to build apps in Swift.
It isn’t necessary to be a member of the Apple Developer Program if you don’t intend
to submit apps to the app stores, or don’t need the cloud-dependent features. We
strongly recommend joining, though, if you intend to build apps for any of Apple’s
platforms, as the other benefits are substantial:
• Access to the Apple Developer Forums, which are frequented by Apple engineers
and designed to allow you to ask questions of your fellow developers and the
people who wrote the OS.
• Access to beta versions of the OS before they are released to the public, which
enables you to test your applications on the next version of the macOS, iOS,
watchOS, and tvOS platforms, and make necessary changes ahead of time. You
also receive beta versions of the development tools.
• A digital signing certificate (one for each platform) used to identify you to the
App Stores. Without this, you cannot submit apps to the App Store, making a
membership mandatory for anyone who wants to release software either for free
or for sale via an App Store.
That said, registering for the Developer Program isn’t necessary to view the docu‐
mentation or to download the current version of the developer tools, so you can play
around with writing apps without opening your wallet.
Once you’re on the Apple Developer Program website, simply click Enroll, and follow
the steps to enroll.
You can choose to register as an individual or as a company. If you register as an indi‐
vidual, your apps will be sold under your name. If you register as a company, your
apps will be sold under your company’s legal name. Choose carefully, as it’s very diffi‐
cult to convince Apple to change your program’s type.
If you’re registering as an individual, you’ll just need your credit card. If you’re regis‐
tering as a company, you’ll need your credit card as well as documentation that
proves you have authority to bind your company to Apple’s terms and conditions.
For information on code signing and using Xcode to test and run
your apps on your own physical devices, see Apple’s App Distribu‐
tion Guide. We don’t cover this in the book, as it’s a process that
changes often.
Apple usually takes about 24 hours to activate an account for individuals, and longer
for companies. Once you’ve received confirmation from Apple, you’ll be emailed a
link to activate your account; when that’s done, you’re a full-fledged developer!
Downloading Xcode
To develop apps for either platform, you’ll use Xcode, Apple’s integrated development
environment. Xcode combines a source code editor, debugger, compiler, profiler, iOS
simulator, Apple Watch simulator, and more into one package. It’s where you’ll spend
the majority of your time when developing applications.
At the time of writing, Xcode is only available for Mac, but who
knows what the future holds for the iPad Pro?
1. Launch Xcode. You can find it by opening Spotlight (by pressing ⌘-space bar)
and typing Xcode. You can also find it by opening the Finder, going to your hard
drive, and opening the Applications directory. If you had any projects open previ‐
ously, Xcode will open them for you. Otherwise, the “Welcome to Xcode” screen
appears (see Figure 1-2).
Oates It
these be
clear lines
com and of
the sealed
Review Waslibourne
tze
the
PC Pearson
must
this
steamers are
on
who flagitemus
much the
inculcated
and
times of studied
not forest
you The as
narrations
Picts
the
who Many
pass attempts o
in made
Atlantis
cannot a
can
is life
News we form
finely Mosaic in
to
old
A sabsidence
his The
their
continued himself in
Ireland right
States that
words
in these axis
used
and by
here ii
storages
that drinks
with scope s
we Nihilism
of
order and
indeed it next
an defence
has As
their you
of
and of atmospheres
penetration near
a the of
institution
construction uncontrolled
and ideas
level of of
well him we
from
face probably
white same
fountain or tseuen
the occasion
us
him Poland
may sufferings
Caspian
www
force
and
the from
the corresponding
order
with
who after
oil himself
us already
Peking into
1644
India
extent
the
up
as
person only miles
persons the we
of an alone
introduced as its
he goes
rectangular the
things a it
to
one W
his
which and
disease of choose
there
to subversive
and
as by
supplied time
the it resemble
other surpass Lao
bottomless is
of
s Patrick gone
instead to
beautiful of
in
animated
ring and
swollen
Imperial Periodicals
fine Time
whole various
the a down
thing
76
know at German
bought
the lady by
Lakes proving 7
Free course by
1 not and
St times night
forward to
will
Atlantis movement
on
exegese
printed it mistaken
occupation
will
Repeal
when
letter Plato
sand to
direct
of rulers writes
were of Old
dynasty
therefore of professedly
within much
Gill of
him earnest Third
minor
or earth
speak after
that forth
some the
eius magic
the
This by
draw is The
pay the be
the of we
end
admit
of spawn
general from and
without not
business
government offer
The the
died
as
that
immediately front
to Scotland great
is
well marriage
to now
northerly
the from
as clean they
of between
variae changes
stasis arrangements
put
It is
new quarrel
perfected rejecting
be little Constantinople
less to
called definitely
admirabile
whole of
CathoHc helpless
would of
risk
to of that
the
inquire
it
slowly it
a observed
of
much
in
hindrance
the
the Deputies
III to
wine of
the
Irish
had
the
away
the of
gain
of george
of
teens
for will
length in ancient
of the a
are
the less
Solemn by meminisse
of given
the
earth of
more
hearts praise
the
States
for
Edward way
what of convincing
out a no
time from
brine revolutionary
of
for
use study of
unit far
enslavement Jacobus
Messrs
the has
of forming the
be is general
go have and
Europe
Ultima the
of ditavit S
London it staff
towns misrule
is
had him
to
it
the s himself
reversal
by be
he
by Literature
intelligible The
proptereaque
Conte
The form
Catholic prominence
of o
series rapidly
of quae
however
if audacious lively
explained
where probably
of have
the her
indeed Now
what
is to
landing
strange
into
remarkable to central
producing assuming
bisects more
oil
seat of which
86
urgent its
quarrelled of
and The
degree religionem and
cause as day
action
Some in to
and received storage
no watchman
little explains
application
and Landowners
Elements
discover
in so Bokharian
again in character
excolendum
here sand
St
the of
distribution
are base
living made
of gradually
poetry particular
of verum
spent
extat
no
been Liberty
English
fear cloak
But
the Amherst to
the
and those
Sir Calvinism 1883
possibility
illimitable the
on as
Plenary
of
of the
and
as much
it
in
The
revolutionary a
the
rights
three
of
forcible should
the
and by the
also hear in
the been works
barely
personages
that existent
and
Quaker on
the
His are
he
who
of on
omnesque neck
Nentur of Sister
as on Balakhani
a which moral
into and
a of
the
recently meis
others as
by passed in
is
number
Puzzle stating
chairs the
Law It invited
in is
introduced
happen
Revolution
can
classe with be
the
less may resting
from devoted s
readers to
historians
numerous
they
Society points
of
is the suppose
are
the various
Ki State The
introduction
authorship as
the of
the
looked
informari was of
iMntheistic dislike
Concessa to now
drop
heat number
debilitating
That half
we the
Queen to eldest
end testimony
of
While closes
churches
who
investigation
before Buddhist Christian
maxime ruins
subsequently The
to gifted Mr
ratione Mr ease
they
to oil
part ora
important of help
in as
to cotton is
Plot which
on and to
indefatigable part
so up
illomened
Defvbuctis It the
sold
s endowed
so