Professional Documents
Culture Documents
Textbook Learning Swift Building Apps For Macos Ios and Beyond 2Nd Edition Paris Buttfield Addison Ebook All Chapter PDF
Textbook Learning Swift Building Apps For Macos Ios and Beyond 2Nd Edition Paris Buttfield Addison Ebook All Chapter PDF
https://textbookfull.com/product/learning-swift-building-apps-
for-osx-ios-and-beyond-jon-manning/
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/
https://textbookfull.com/product/head-first-swift-1st-edition-
gray-anthony-manning-jon-buttfield-addison-paris/
https://textbookfull.com/product/unity-game-development-cookbook-
essentials-for-every-game-1-converted-edition-paris-buttfield-
addison/
iOS 11 Swift Programming Cookbook Solutions and
Examples for iOS Apps 1st Edition Vandad Nahavandipoor
https://textbookfull.com/product/ios-11-swift-programming-
cookbook-solutions-and-examples-for-ios-apps-1st-edition-vandad-
nahavandipoor/
https://textbookfull.com/product/swift-4-for-absolute-beginners-
develop-apps-for-ios-4th-edition-stefan-kaczmarek/
https://textbookfull.com/product/developing-inclusive-mobile-
apps-building-accessible-apps-for-ios-and-android-1st-edition-
rob-whitaker/
https://textbookfull.com/product/realm-building-modern-swift-
apps-with-realm-database-2nd-edition-marin-todorov/
https://textbookfull.com/product/ios-10-sdk-development-creating-
iphone-and-ipad-apps-with-swift-chris-adamson/
2 n ve r s
Co
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‐
tions@oreilly.com.
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 lab@secretlab.com.au 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).
If you don’t have a domain name, enter anything you like, as long as it looks
like a backward domain name (e.g., com.mycompany will work).
If you’re writing an application for the Mac App Store, you’ll also be prompted
for the App Store category (whether it’s a game, an educational app, a social net‐
working app, or something else).
Depending on the template, you may also be asked for other information (e.g.,
the file extension for your documents if you are creating a document-aware
application, such as a Mac app). You’ll also be asked which language you want to
use; because this book is about Swift, you should probably choose Swift! The
additional information needed for this project is covered in the following steps.
5. Make the application run on the iPhone by choosing iPhone from the Devices
drop-down list.
7. Choose where to save the project. Select a location that suits you. We recommend
putting all your work related to this book (and other Swift programming learning
you might do) in one folder. You might notice a little checkbox for Source Con‐
trol; this creates a source code control repository for your code, giving you a
place where you can save and manage different versions of your code as you cre‐
ate them. While in general this is a good idea to use, for this example project,
make sure this is unchecked.
Once you’ve done this, Xcode will open the project, and you can now start using the
entire Xcode interface, as shown in Figure 1-5.
The editor
The Xcode editor (Figure 1-6) is where you’ll be spending most of your time. All
source code editing, interface design, and project configuration take place in this sec‐
tion of the application, which changes depending on which file you have open.
If you’re editing source code, the editor is a text editor, with code completion, syntax
highlighting, and all the usual features that developers have come to expect from an
integrated development environment. If you’re modifying a user interface, the editor
becomes a visual editor, allowing you to drag around the components of your inter‐
face. Other kinds of files have their own specialized editors as well.
When you first create a project, the editor will start by showing the project settings, as
seen in Figure 1-6.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.