0% found this document useful (0 votes)
69 views

Python Pocket Reference 5th Edition - FreePdfBook

Python Pocket Reference 5th Edition

Uploaded by

Mateo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Python Pocket Reference 5th Edition - FreePdfBook

Python Pocket Reference 5th Edition

Uploaded by

Mateo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Swift for

Beginners
DEVELOP AND DESIGN

Boisy G. Pitre

PEACHPIT PRESS
WWW.PEACHPIT.COM
Swift for Beginners: Develop and Design
Boisy G. Pitre

Peachpit Press
www.peachpit.com

To report errors, please send a note to errata@peachpit.com.

Peachpit Press is a division of Pearson Education.

Copyright 2015 by Boisy G. Pitre

Editor: Robyn G. Thomas


Copyeditor: Darren Meiss
Proofreader: Nancy Bell
Technical editor: Steve Phillips
Compositor: Danielle Foster
Indexer: Valerie Haynes Perry
Cover design: Aren Straiger

Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechani-
cal, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting
permission for reprints and excerpts, contact permissions@peachpit.com.

Notice of Liability
The information in this book is distributed on an As Is basis, without warranty. While every precaution has been taken in
the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity with respect to
any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the
computer software and hardware products described in it.

Trademarks
Apple, Cocoa, Cocoa Touch, Objective-C, OS X, and Xcode are registered trademarks of Apple Inc., registered in the U.S. and
other countries. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations
appear as requested by the owner of the trademark. All other product names and services identied throughout this book
are used in editorial fashion only and for the benet of such companies with no intention of infringement of the trademark.
No such use, or the use of any trade name, is intended to convey endorsement or other aliation with this book.

ISBN-13: 978-0-134-04470-5
ISBN-10: 0-134-04470-3

987654321

Printed and bound in the United States of America


To the girls: Toni, Hope, Heidi, Lillian, Sophie, and Belle
ACKNOWLEDGMENTS
When creating a book, it truly takes a village, and I could not have had better support from
the sta at Peachpit Press. Many thanks go to executive editor, Cli Colby at Peachpit for
providing me the opportunity; editor Robyn Thomas for her immensely helpful and invalu-
able editing skills and for keeping the project on track; technical editor Steve Phillips who
meticulously commented on drafts of the book for technical correctness and whose contri-
butions undoubtedly made this work better.
During my writing, Ive drawn inspiration from the works of a number of friends who
areauthors in the iOS and Mac OS developer community: Chris Adamson, Bill Cheeseman,
Bill Dudney, Daniel Steinberg, and Richard Warren.
I would be remiss if I didnt mention the MacTech Conference dynamic duo Ed Marczak
and Neil Ticktin, as well as CocoaConf maestro Dave Klein, for the writing and speaking
opportunities that they have provided me at those venues.
A tip of the hat to James Dempsey, whose band, the Breakpoints, and their excellent
Backtrace album fueled several long writing and review sessions with their rollicking tunes.
Java Square Caf in downtown Opelousas, Louisiana provided a great place to write as well as
tasty lattes. Also, thanks to Dave et Rays Camp Jam/Supper Club and my friends there who
served as inspiration for several of the coding examples I used.
Much appreciation goes to the minds at Apple for creating Swift, along with a host of
great products over the years that have enhanced my own productivity and that of many,
many others.
Finally, many thanks to my family, especially my wife, Toni, whose patience and
encouragement while I worked on this book was abundant.

iv ACKNOWLEDGMENTS
ABOUT THE AUTHOR
Boisy G. Pitre is Aectivas Mobile Visionary and lead iOS developer, where his work has led
to the creation of the rst mobile SDK for delivering emotions to mobile devices for the lead-
ing emotion technology company and spin-o of the MIT Media Lab. Prior to that he was
a member of the Mac Products Group at Nuance Communications where he worked with a
team of developers on Dragon Dictate.
He also owns Tee-Boy, a software company focusing on Mac and iOS applications for the
weather and data acquisition markets, and has authored the monthly Developer to Developer
column in MacTech Magazine.
Along with Bill Loguidice, Boisy co-authored the book CoCo: The Colorful History of
Tandys Underdog Computer (2013), published by Taylor & Francis.
Boisy holds a Master of Science in Computer Science from the University of Louisi-
ana at Lafayette, and resides in the quiet countryside of Prairie Ronde, Louisiana. Besides
Mac and iOS development, his hobbies and interests include retro-computing, ham radio,
vending machine and arcade game restoration, farming, and playing the French music of
SouthLouisiana.

ABOUT THE AUTHOR v


CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Welcome to Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv

SECTION I THE BASICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

CHAPTER 1 INTRODUCING SWIFT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4


Evolutionary, yet Revolutionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Preparing for Success . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Tools of the Trade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Interacting with Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Ready, Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Diving into Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Help and Quit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Hello World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
The Power of Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Constants Are Consistent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
This Thing Called a Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Testing the Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Can a Leopard Change Its Stripes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Being Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Strings and Things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Stringing Things Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Characters Have Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Math and More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Mixing Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Numeric Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
True or False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Printing Made Easy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Using Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Grouping Data with Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Optionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

CHAPTER 2 WORKING WITH COLLECTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32


The Candy Jar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Birds of a Feather . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Extending the Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Replacing and Removing Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

vi CONTENTS
Inserting Values at a Specic Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Combining Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
The Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Looking Up an Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Adding an Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Updating an Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Removing an Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Arrays of Arrays? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Starting from Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
The Empty Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
The Empty Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Iterating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Array Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Dictionary Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

CHAPTER 3 TAKING CONTROL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56


For What Its Worth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Counting On It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Inclusive or Exclusive? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
For Old Times Sake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Writing Shorthand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Its Time to Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Making Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
The Decisiveness of If . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
When One Choice Is Not Enough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Switching Things Around . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
While You Were Away . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Inspecting Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Give Me a Break! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

CHAPTER 4 WRITING FUNCTIONS AND CLOSURES . . . . . . . . . . . . . . . . . . . . . . . 82


The Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Coding the Function in Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Exercising the Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
More Than Just Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Parameters Ad Nauseam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Functions Fly First Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Throw Me a Function, Mister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
A Function in a Function in a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Default Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Whats in a Name? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

CONTENTS vii
When Its Good Enough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
To Use or Not to Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Dont Change My Parameters! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
The Ins and Outs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Bringing Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Summing It Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Stay Classy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

CHAPTER 5 ORGANIZING WITH CLASSES AND STRUCTURES . . . . . . . . . . . . . 114


Objects Are Everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Swift Objects Are Classy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Knock, Knock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Let There Be Objects! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Opening and Closing the Door . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Locking and Unlocking the Door . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Examining the Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Door Diversity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Painting the Door . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Modeling the Base Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Creating the Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Instantiating the Subclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Convenience Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Structural Integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Value Types vs. Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Looking Back, Looking Ahead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

CHAPTER 6 FORMALIZING WITH PROTOCOLS AND EXTENSIONS . . . . . . . . 148


Following Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Class or Protocol? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
More Than Just Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Adopting Multiple Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Protocols Can Inherit, Too . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Extending with Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Extending Basic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Using Closures in Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

viii CONTENTS
SECTION II DEVELOPING WITH SWIFT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

CHAPTER 7 WORKING WITH XCODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172


Xcodes Pedigree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Creating Your First Swift Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Diving Down . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Interacting with the Project Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Its Alive! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Piquing Your Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Making Room . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Building the UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Tidying Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Class Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Hooking It Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
You Made an App! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

CHAPTER 8 MAKING A BETTER APP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192


Its the Little Things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Show Me the Money . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Remember the Optional? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Unwrapping Optionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Looking Better . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Formatting: A Dierent Technique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Compounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Hooking Things Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Testing Your Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
When Things Go Wrong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Wheres the Bug? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
At the Breaking Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
The Confounding Compound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
The Value of Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
The Unit Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Crafting a Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
When Tests Fail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Tests That Always Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

CHAPTER 9 GOING MOBILE WITH SWIFT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218


In Your Pocket vs. on Your Desk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Hows Your Memory? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Thinking About Gameplay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Designing the UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

CONTENTS ix
Creating the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Building the User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Creating the Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Running in the Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Setting Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
The Model-View-Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Coding the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
The Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
The View Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
The Model Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Overridable Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Game Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Winning and Losing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Back to the Storyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Time to Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

CHAPTER 10 ADVANCING AHEAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248


Memory Management in Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Value vs. Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
The Reference Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Only the Strong Survive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Put It in a Letter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
The Test Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Breaking the Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Cycles in Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Thanks for the Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Thinking Logically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
To Be or NOT to Be . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Combining with AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
One Way OR the Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Overloading Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Equal vs. Identical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Scripting and Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Editing the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Setting Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Calling S.O.S. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
And Now, Your Journey Begins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Study Apples Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

x CONTENTS
Join Apples Developer Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Become a Part of the Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Never Stop Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Bon Voyage! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .278

CONTENTS xi
INTRODUCTION
Welcome to Swift for Beginners! Swift is Apples new language for developing apps for iOS
and Mac OS, and it is destined to become the premier computer language in the mobile
anddesktop space. As a new computer language, Swift has the allure of a shiny new car
everybody wants to see it up close, kick the tires, and take it for a spin down the road. Thats
probably why youre reading this bookyouve heard about Swift and decided to see what
all the fuss is about.
The notion that Swift is an easy language to use and learn certainly has merit, especially
when compared to the capable but harder-to-learn programming language its replacing:
Objective-C. Apple has long used Objective-C as its language of choice for developing soft-
ware on its platforms, but that is changing with the introduction of Swift.
Not only is Swift easy to learn, its extremely powerful. Youll get a taste of some of that
power here in this book.

WHO IS THIS BOOK FOR?


This book was written for the beginner in mind. In a sense, were all beginners with Swift
because its such a new language. However, many will want to learn Swift as a rst or second
computer language, many of whom havent had any exposure to Objective-C or related lan-
guages, C and C++.
Ideally, the reader will have some understanding and experience with a computer lan-
guage; even so, the book is styled to appeal to the neophyte who is suciently motivated
to learn. More experienced developers will probably nd the rst few chapters to be review
material and light reading because the concepts are ubiquitous among many computer lan-
guages but nonetheless important to introduce Swift to the beginner.
No matter your skill level or prior experience, Swift for Beginners will appeal to anyone
who wants to learn about Swift.

HOW TO USE THIS BOOK


Like other books of its kind, Swift for Beginners is best read from start to nish. The material
in subsequent chapters tends to build on the knowledge attained from previous ones. How-
ever, with few exceptions, code examples are conned to a single chapter.
The book is sized to provide a good amount of material, but not so much as to over-
whelm the reader. Interspersed between the text are a copious number of screenshots to
guide the beginner through the ins and outs of Swift as well as the Xcode tool chain.

HOW YOU WILL LEARN


The best way to learn Swift is to use it, and using Swift is emphasized throughout the book
with plenty of code and examples.

xii INTRODUCTION
Each chapter contains code that builds on the concepts presented. Swift has two interac-
tive environments you will use to test out concepts and gain understanding of the language:
the REPL and playgrounds. Later, youll build two simple but complete apps: a loan calcula-
tor for Mac OS and a memory game for iOS.
Swift concepts will be introduced throughout the textclasses, functions, closures, and
more, all the way to the very last chapter. Youre encouraged to take your time and read each
chapter at your leisure, even rereading if necessary, before moving on to the next one.
Source code for all the chapters is available at www.peachpit.com/swiftbeginners.
Youcan download the code for each chapter, which cuts down considerably on typing;
nonetheless, I am a rm believer in typing in the code. By doing so, you gain insight and
comprehension you might otherwise miss if you just read along and rely on the downloaded
code. Make the time to type in all of the code examples.
For clarity, code and other constructs such as class names are displayed in monospace font.
Highlighted code throughout the book identies the portions of the code that are
intended for you to type:
1> let candyJar = ["Peppermints", "Gooey Bears", "Happy Ranchers"]
candyJar: [String] = 3 values {
[0] = "Peppermints"
[1] = "Gooey Bears"
[2] = "Happy Ranchers"
}
2>

Youll also nd notes containing additional information about the topics.

NOTE: To print or not to print? Remember, simply typing the name of the
item without using print or println is acceptable when using the REPL.
When doing so, the result of the expression is assigned to a temporary
variablein this case $R0.

WHAT YOU WILL LEARN


Ultimately, this book will show you how to use Swift to express your ideas in code. When
you complete the nal chapter, you should have a good head start, as well as a solid under-
standing of what the language oers. Additionally, youll have the skills to begin writing an
app. Both iOS and Mac OS apps are presented as examples in the later chapters.
What this book does not do is provide an all-inclusive, comprehensive compendium on
the Swift programming language. Apples documentation is the best resource for that. Here,
the emphasis is primarily on learning the language itself; various Cocoa frameworks are
touched on where necessary to facilitate the examples but are not heavily emphasized for
their own sake.

INTRODUCTION xiii
WELCOME TO SWIFT
Swift is a fun, new, and easy-to-learn computer language from Apple. With the
knowledge youll gain from this book, you can begin writing apps for iOS and
Mac OS. The main tool youll need to start learning Swift is the Xcode integrated
development environment (IDE). Xcode includes the Swift compiler, as well
as the iOS and Mac OS software development kits (SDKs) that contain all the
infrastructure required to support the apps you develop.

THE TECHNOLOGIES
The following technologies are all part of your journey into the
Swiftlanguage.

SWIFT XCODE LLVM


Swift is the language Xcode is Apples premier Although it works behind
youll learn in this book. environment for writing the scenes within Xcode,
Swift is a modern lan- apps. It includes an editor, LLVM is the compiler
guage designed from the debugger, project man- technology that empow-
ground up to be easy to ager, and the compiler ers the elegance of the
learn as well as power- tool chain needed to take Swift language and turns
ful. It is language that Swift code and turn it into it into the digestible bits
Apple has chosen to fuel runnable code for iOS or and bytes needed by the
the continued growth Mac OS. You can down- processors that power
of apps, which make up load Xcode from Apples Apple devices.
their iOS and Mac OS Mac App Store.
ecosystem.

xiv WELCOME TO SWIFT


THE REPL PLAYGROUNDS
The Read-Eval-Print-Loop (REPL) is a command-line tool The interactivity and immediate results from Xcodes
you can use to try out Swift code quickly. You run it playgrounds are a great way to try out Swift code as
from the Terminal application on Mac OS. you learn the language.

WELCOME TO SWIFT xv
CHAPTER 4

Writing Functions
and Closures
Weve covered a lot up to this point in the book: variables, con-
stants, dictionaries, arrays, looping constructs, control structures,
and the like. Youve used both the REPL command-line interface
and now Xcode 6s playgrounds feature to type in code samples
and explore the language.
Up to this point, however, you have been limited to mostly
experimentation: typing a line or three here and there and
observing the results. Now its time to get more organized with
your code. In this chapter, youll learn how to tidy up your Swift
code into nice clean reusable components called functions.
Lets start this chapter with a fresh, new playground le. If
you havent already done so, launch Xcode 6 and create a new
playground by choosing File > New > Playground, and name it
Chapter 4. Well explore this chapters concepts with contrived
examples in similar fashion to earlier chapters.

83
THE FUNCTION
Think back to your school years again. This time, remember high school algebra. You were
paying attention, werent you? In that class your teacher introduced the concept of the
function. In essence, a function in arithmetic parlance is a mathematical formula that takes
an input, performs a calculation, and provides a result, or output.
Mathematical functions have a specic notation. For example, to convert a Fahrenheit
temperature value to the equivalent Celsius value, you would express that function in this way:

The important parts of the function are:


Name: In this case the functions name is f.
Input, or independent variable: Contains the value that will be used in the function.
Hereits x.
Expression: Everything on the right of the equals sign.
Result: Considered to be the value of f(x) on the left side of the equals sign.
Functions are written in mathematical notation but can be described in natural language.
In English, the sample function could be described as:
A function whose independent variable is x and whose result is the dierence of the
independent variable and 32, with the result being multiplied by 5, with the result being
divided by 9.
The expression is succinct and tidy. The beauty of this function, and functions in
general, is that they can be used over and over again to perform work, and all they need
todo is be called with a parameter. So how does this relate to Swift? Obviously I wouldnt
betalking about functions if they didnt exist in the Swift language. And as youll see,
theycan perform not just mathematical calculations, but a whole lot more.

CODING THE FUNCTION IN SWIFT


Swifts notation for establishing the existence of a function is a little dierent than the
mathematical one you just saw. In general, the syntax for declaring a Swift function is:
func funcName(paramName : type, ...) -> returnType

Take a look at an example to help clarify the syntax. Figure 4.1 shows the code in the
Chapter 4.playground le, along with the function dened on lines 7 through 13. This is the
function discussed earlier, but now in a notation the Swift compiler can understand.

84 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.1 Tempera-
ture conversion as a
Swift function

Start by typing in the following code.


func fahrenheitToCelsius(fahrenheitValue : Double) -> Double {
var result : Double

result = (((fahrenheitValue - 32) * 5) / 9)

return result
}

As you can see on line 7, there is some new syntax to learn. The func keyword is Swifts
way to declare a function. That is followed by the function name (fahrenheitToCelsius),
and the independent variables name, or parameter name in parentheses. Notice that the
parameters type is explicitly declared as Double.
Following the parameter are the two characters ->, which denote that this function is
returning a value of a type (in this case, a Double type), followed by the open curly brace,
which indicates the start of the function.
On line 8, you declare a variable of type Double named result. This will hold the value
that will be given back to anyone who calls the function. Notice it is the same type as the
functions return type declared after the -> on line 7.
The actual mathematical function appears on line 10, with the result of the expres-
sion assigned to result, the local variable declared in line 8. Finally on line 12, the result is
returned to the caller using the return keyword. Any time you wish to exit a function and
return to the calling party, you use return along with the value being returned.
The Results sidebar doesnt show anything in the area where the function was typed.
Thats because a function by itself doesnt do anything. It has the potential to perform some
useful work, but it must be called by a caller. Thats what youll do next.

THE FUNCTION 85
FIGURE 4.2 The result
of calling the newly
created function

EXERCISING THE FUNCTION


Now its time to call on the function you just created. Type in the following two lines of code,
and pay attention to the Results sidebar in Figure 4.2.
var outdoorTemperatureInFahrenheit = 88.2
var outdoorTemperatureInCelsius = fahrenheitToCelsius(outdoorTemperature
p InFahrenheit)

On line 15, youve declared a new variable, outdoorTemperatureInFahrenheit, and set


its value to 88.2 (remember, Swift infers the type in this case as a Double). That value is then
passed to the function on line 16, where a new variable, outdoorTemperatureInCelsius, is
declared, and its value is captured as the result of the function.
The Results sidebar shows that 31.222222 (repeating decimal) is the result of the func-
tion, and indeed, 31.2 degrees Celsius is equivalent to 88.2 degrees Fahrenheit. Neat, isnt it?
You now have a temperature conversion tool right at your ngertips.
Now, heres a little exercise for you to do on your own: Write the inverse method,
celsiusToFahrenheit using the following formula for that conversion:

Go ahead and code it up yourself, but resist the urge to peek ahead. Dont look until
youve written the function, and then check your work against the following code and in
Figure 4.3.

86 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.3 Declaring
the inverse function,
celsiusToFahrenheit

func celsiusToFahrenheit(celsiusValue : Double) -> Double {


var result : Double

result = (((celsiusValue * 9) / 5) + 32)

return result
}

outdoorTemperatureInFahrenheit = celsiusToFahrenheit(outdoorTemperature
p InCelsius)

The inverse function on lines 18 through 24 simply implements the Celsius to Fahrenheit
formula and returns the result. Passing in the Celsius value of 31.22222 on line 26, you can
see that the result is the original Fahrenheit value, 88.2.
Youve just created two functions that do something useful: temperature conversions.
Feel free to experiment with other values to see how they change between the two related
functions.

THE FUNCTION 87
FIGURE 4.4 A multi-
parameter function

MORE THAN JUST NUMBERS


The notion of a function in Swift is more than just the mathematical concept we have
discussed. In a broad sense, Swift functions are more exible and robust in that they can
accept more than just one parameter, and even accept types other than numeric ones.
Consider creating a function that takes more than one parameter and returns something
other than a Double (Figure 4.4).
func buildASentence(subject : String, verb : String, noun : String) -> String {
return subject + " " + verb + " " + noun + "!"
}

buildASentence("Swift", "is", "cool")


buildASentence("I", "love", "languages")

After typing in lines 28 through 33, examine your work. On line 28, you declared a new
function, buildASentence, with not one but three parameters: subject, verb, and noun, all
of which are String types. The function also returns a String type as well. On line 29, the
concatenation of those three parameters, interspersed with spaces to make the sentence
readable, is what is returned.
For clarity, the function is called twice on lines 32 and 33, resulting in the sentences in
the Results sidebar. Feel free to replace the parameters with values of your own liking and
view the results interactively.

88 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.5 Variable
parameter passing in a
function

PARAMETERS AD NAUSEAM
Imagine youre writing the next big banking app for the Mac, and you want to create a way
to add some arbitrary number of account balances. Something so mundane can be done a
number of ways, but you want to write a Swift function to do the addition. The problem is
you dont know how many accounts will need to be summed at any given time.
Enter Swifts variable parameter passing notation. It provides you with a way to tell Swift,
I dont know how many parameters Ill need to pass to this function, so accept as many as
I will give. Type in the following code, which is shown in action on lines 35 through 48 in
Figure 4.5.
// Parameters Ad Nauseam
func addMyAccountBalances(balances : Double...) -> Double {
var result : Double = 0

for balance in balances {


result += balance
}

THE FUNCTION 89
FIGURE 4.6 Adding
additional variable
parameters results in
an error.

return result
}

addMyAccountBalances(77.87)
addMyAccountBalances(10.52, 11.30, 100.60)
addMyAccountBalances(345.12, 1000.80, 233.10, 104.80, 99.90)

This functions parameter, known as a variadic parameter, can represent an unknown


number of parameters.
On line 36, our balances parameter is declared as a Double followed by the ellipsis (...)
and returns a Double. The presence of the ellipsis is the clue: It tells Swift to expect one or
more parameters of type Double when this function is called.
The function is called three times on lines 46 through 48, each with a dierent number of
bank balances. The totals for each appear in the Results sidebar.
You might be tempted to add additional variadic parameters in a function. Figure 4.6
shows an attempt to extend addMyAccountBalances with a second variadic parameter, but it
results in a Swift error.

90 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.7 Functions
to find the largest and
smallest balance

This is a no-no, and Swift will quickly shut you down with an error. Only the last
parameter of a function may contain the ellipsis to indicate a variadic parameter. All
otherparameters must refer to a single quantity.
Since were on the theme of bank accounts, add two more functions: one that will nd
the largest balance in a given list of balances, and another that will nd the smallest balance.
Type the following code, which is shown on lines 50 through 75 in Figure 4.7.
func findLargestBalance(balances : Double...) -> Double {
var result : Double = -Double.infinity

for balance in balances {


if balance > result {
result = balance
}
}

return result
}

THE FUNCTION 91
func findSmallestBalance(balances : Double...) -> Double {
var result : Double = Double.infinity

for balance in balances {


if balance < result {
result = balance
}
}

return result
}

findLargestBalance(345.12, 1000.80, 233.10, 104.80, 99.90)


findSmallestBalance(345.12, 1000.80, 233.10, 104.80, 99.90)

Both functions iterate through the parameter list to nd the largest and smallest balance.
Unless you have an account with plus or minus innity of your favorite currency, these func-
tions will work well. On lines 74 and 75, both functions are tested with the same balances
used earlier, and the Results sidebar conrms their correctness.

FUNCTIONS FLY FIRST CLASS


One of the powerful features of Swift functions is that they are rst-class objects. Sounds
pretty fancy, doesnt it? What that really means is that you can handle a function just like
any other value. You can assign a function to a constant, pass a function as a parameter to
another function, and even return a function from a function!
To illustrate this idea, consider the act of depositing a check into your bank account, as
well as withdrawing an amount. Every Monday, an amount is deposited, and every Friday,
another amount is withdrawn. Instead of tying the day directly to the function name of the
deposit or withdrawal, use a constant to point to the function for the appropriate day. The
code on lines 77 through 94 in Figure 4.8 provides an example.
var account1 = ( "State Bank Personal", 1011.10 )
var account2 = ( "State Bank Business", 24309.63 )

func deposit(amount : Double, account : (name : String, balance : Double)) ->


p (String, Double) {
var newBalance : Double = account.balance + amount
return (account.name, newBalance)
}

92 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.8
Demonstrating
functions as first-class
types

func withdraw(amount : Double, account : (name : String, balance : Double)) ->


p (String, Double) {
var newBalance : Double = account.balance - amount
return (account.name, newBalance)
}

let mondayTransaction = deposit


let fridayTransaction = withdraw

let mondayBalance = mondayTransaction(300.0, account1)


let fridayBalance = fridayTransaction(1200, account2)

For starters, you create two accounts on lines 77 and 78. Each account is a tuple consist-
ing of an account name and balance.
On line 80, a function is declared named deposit that takes two parameters: the amount
(a Double) and a tuple named account. The tuple has two members: name, which is of type
String, and balance, which is a Double that represents the funds in that account. The same
tuple type is also declared as the return type.

THE FUNCTION 93
At line 81, a variable named newBalance is declared, and its value is assigned the sum of
the balance member of the account tuple and the amount variable that is passed. The tuple
result is constructed on line 82 and returned.
The function on line 85 is named dierently (withdraw) but is eectively the same, save
for the subtraction that takes place on line 86.
On lines 90 and 91, two new constants are declared and assigned to the functions
respectively by name: deposit and withdraw. Since deposits happen on a Monday, the
mondayTransaction is assigned the deposit function. Likewise, withdrawals are on Friday,
and the fridayTransaction constant is assigned the withdraw function.
Lines 93 and 94 show the results of passing the account1 and account2 tuples to the
mondayTransaction and fridayTransaction constants, which are in essence the functions
deposit and withdraw. The Results sidebar bears out the result, and youve just called the
two functions by referring to the constants.

THROW ME A FUNCTION, MISTER


Just as a function can return an Int, Double, or String, a function can also return another
function. Your head starts hurting just thinking about the possibilities, doesnt it? Actually,
its not as hard as it sounds. Check out lines 96 through 102 in Figure 4.9.
func chooseTransaction(transaction: String) -> (Double, (String, Double)) ->
p (String, Double) {
if transaction == "Deposit" {
return deposit
}

return withdraw
}

On line 96, the function chooseTransaction takes a String as a parameter, which it uses
to deduce the type of banking transaction. That same function returns a function, which
itself takes a Double, and a tuple of String and Double, and returns a tuple of String and
Double. Phew!
Thats a mouthful. Lets take a moment to look at that line closer and break it down a
bit. The line begins with the denition of the function and its sole parameter: transaction,
followed by the -> characters indicating the return type:
func chooseTransaction(transaction: String) ->

After that is the return type, which is a function that takes two parameters: the Double,
and a tuple of Double and String, as well as the function return characters ->:
(Double, (String, Double)) ->

And nally, the return type of the returned function, a tuple of String and Double.

94 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.9
Returning a function
from a function

What functions did you write that meet this criteria? The deposit and withdraw func-
tions, of course! Look at lines 80 and 85. Those two functions are bank transactions that
were used earlier. Since they are dened as functions that take two parameters (a Double and
a tuple of String and Double) and return a tuple of Double and String, they are appropriate
candidates for return values in the chooseTransaction function on line 96.
Back to the chooseTransaction function: On line 97, the transaction parameter,
whichis a String, is compared against the constant string "Deposit" and if a match is made,
the deposit function is returned on line 98; otherwise, the withdraw function is returned on
line 101.
Ok, so you have a function which itself returns one of two possible functions. How do
you use it? Do you capture the function in another variable and call it?
Actually, there are two ways this can be done (Figure 4.10).
// option 1: capture the function in a constant and call it
let myTransaction = chooseTransaction("Deposit")
myTransaction(225.33, account2)

// option 2: call the function result directly


chooseTransaction("Withdraw")(63.17, account1)

THE FUNCTION 95
FIGURE 4.10 Calling
the returned function
in two different ways

On line 105 you can see that the returned function for making deposits is captured in
the constant myTransaction, which is then called on line 106 with account2 increasing its
amount by $225.33.
The alternate style is on line 109. There, the chooseTransaction function is being
called to gain access to the withdraw function. Instead of assigning the result to a constant,
however, the returned function is immediately pressed into service with the parameters
63.17 and the rst account, account1. The results are the same in the Results sidebar: The
withdraw function is called and the balance is adjusted.

A FUNCTION IN A FUNCTION IN A
If functions returned by functions and assigned to constants isnt enough of an enigma for
you, how about declaring a function inside of another function? Yes, such a thing exists.
Theyre called nested functions.
Nested functions are useful when you want to isolate, or hide, specic functionality that
doesnt need to be exposed to outer layers. Take, for instance, the code in Figure 4.11.
// nested function example
func bankVault(passcode : String) -> String {
func openBankVault(Void) -> String {
return "Vault opened"
}

96 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.11 Nested
functions in action

func closeBankVault(Void) -> String {


return "Vault closed"
}
if passcode == "secret" {
return openBankVault()
}
else {
return closeBankVault()
}
}

println(bankVault("wrongsecret"))
println(bankVault("secret"))

On line 112, a new function, bankVault, is dened. It takes a single parameter, passcode,
which is a String, and returns a String.
Lines 113 and 116 dene two functions inside of the bankVault function: openBankVault
and closeBankVault. Both of these functions take no parameter and return a String.
On line 119, the passcode parameter is compared with the string "secret" and if a match
is made, the bank vault is opened by calling the openBankVault function. Otherwise, the
bank vault remains closed.

THE FUNCTION 97
FIGURE 4.12 The result
of attempting to call a
nested function from a
different scope

INTO THE VOID

On lines 113 and 116, youll notice a new Swift keyword: Void. It means exactly what you
might think: emptiness. The Void keyword is used mostly as a placeholder when declaring
empty parameter lists, and is optional in this case. However, be aware of it because you
will be seeing more of it later.

Lines 127 and 128 show the result of calling the bankVault method with an incorrect and
correct passcode. Whats important to realize is that the openBankVault and closeBankVault
functions are enclosed by the bankVault function, and are not known outside of
thatfunction.
If you were to attempt to call either openBankVault or closeBankVault outside of the
bankVault function, you would get an error. Thats because those functions are not in scope.
They are, in eect, hidden by the bankVault function and are unable to be called from the
outside. Figure 4.12 illustrates an attempt to call one of these nested functions.
In general, the obvious benet of nesting functions within functions is that it prevents
the unnecessary exposing of functionality. In Figure 4.12, The bankVault function is the sole
gateway to opening and closing the vault, and the functions that perform the work are iso-
lated within that function. Always consider this when designing functions that are intended
to work together.

98 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.13 Using
default parameters in
afunction

DEFAULT PARAMETERS
As youve just seen, Swift functions provide a rich area for utility and experimentation. A lot
can be done with functions and their parameters to model real-world problems. Functions
provide another interesting feature called default parameter values, which allow you to
declare functions that have parameters containing a prelled value.
Lets say you want to create a function that writes checks. Your function would take two
parameters: a payee (the person or business to whom the check is written) and the amount.
Of course, in the real world, you will always want to know these two pieces of information,
but for now, think of a function that would assume a default payee and amount in the event
the information wasnt passed.
Figure 4.13 shows such a function on lines 130 through 132. The writeCheck function
takes two String parameters, the payee and amount, and returns a String that is simply a
sentence describing how the check is written.
func writeCheck(payee : String = "Unknown", amount : String = "10.00") ->
p String {
return "Check payable to " + payee + " for $" + amount
}

writeCheck()
writeCheck(payee : "Donna Soileau")
writeCheck(payee : "John Miller", amount : "45.00")
THE FUNCTION 99
Take note of the declaration of the function on line 130:
func writeCheck(payee : String = "Unknown", amount : String = "10.00") ->
p String

What you havent seen before now is the assignment of the parameters to actual values
(in this case, payee is being set to "Unknown" by default and amount is being set to "10.00").
This is how you can write a function to take default parameterssimply assign the param-
eter name to a value!
So how do you call this function? Lines 134 through 136 show three dierent ways:
Line 134 passes no parameters when calling the function.
Line 135 passes a single parameter.
Line 136 passes both parameters.
In the case where no parameters are passed, the default values are used to construct the
returned String. In the other two cases, the passed parameter values are used in place of
thedefault values, and you can view the results of the calls in the Results sidebar.
Another observation: When calling a function set up to accept default parameters, you
must pass the parameter name and a colon as part of that parameter. On line 135, only one
parameter is used:
writeCheck(payee : "Donna Soileau")

And on line 136, both parameter names are used:


writeCheck(payee : "John Miller", amount : "45.00")

Default parameters give you the exibility of using a known value instead of taking the
extra eort to pass it explicitly. Theyre not necessarily applicable for every function out
there, but they do come in handy at times.

WHATS IN A NAME?
As Swift functions go, declaring them is easy, as youve seen. In some cases, however, what
really composes the function name is more than just the text following the keyword func.
Each parameter in a Swift function can have an optional external parameter preceding
the parameter name. External names give additional clarity and description to a function
name. Consider another check writing function in Figure 4.14, lines 138 through 140.
func writeCheck(payer : String, payee : String, amount : Double) -> String {
return "Check payable from \(payer) to \(payee) for $\(amount)"
}

writeCheck("Dave Johnson", "Coz Fontenot", 1000.0)

100 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.14 A func-
tion without external
parameter names

This function is dierent from the earlier check writing function on lines 130 through
132 in two ways:
An additional parameter named payer to indicate who the check is coming from
No default parameters
On line 142, the new writeCheck function is called with three parameters: two String
values and a Double value. From the name of the function, its purpose is clearly to write
a check. When writing a check, you need to know several things: who the check is being
written for; who is writing the check; and for how much? A good guess is that the Double
parameter is the amount, which is a number. But without actually looking at the function
declaration itself, how would you know what the two String parameters actually mean?
Even if you were to deduce that they are the payer and payee, how do you know which is
which, and in which order to pass the parameters?

THE FUNCTION 101


FIGURE 4.15 A function
with external param-
eter names

External parameter names solve this problem by adding an additional name to each
parameter that must be passed when calling the function, which makes very clear to anyone
reading the calling function what the intention is and the purpose of each parameter.
Figure4.15 illustrates this quite well.
func writeBetterCheck(from payer : String, to payee : String, total amount :
p Double) -> String {
return "Check payable from \(payer) to \(payee) for $\(amount)"
}

writeBetterCheck(from : "Fred Charlie", to: "Ryan Hanks", total : 1350.0)

On line 144, you declare a function, writeBetterCheck, which takes the same number of
parameters as the function on line 138. However, each of the parameters in the new function
now has its own external parameter: from, to, and total. The original parameter names are
still there, of course, used inside the function itself to reference the assigned values.
This extra bit of typing pays o on line 148, when the writeBetterCheck function is
called. Looking at that line of code alone, the order of the parameters and what they indicate
is clear: Write a check from Fred Charlie to Ryan Hanks for a total of $1350.

102 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.16 Using the
shorthand external
parameter syntax

WHEN ITS GOOD ENOUGH


External parameter names bring clarity to functions, but they can feel somewhat redundant
and clumsy as you search for something to accompany the parameter name. Actually, you
may nd that in certain cases, the parameter name is descriptive enough to act as the exter-
nal parameter name. Swift allows you to use the parameter name as an external name, too,
with a special syntax: the # character.
Instead of providing an external parameter name, simply prepend the # character to the
parameter name, and use that name when calling the new function writeBestCheck, as
done on line 150 in Figure 4.16. This is known as shorthand external parameter naming.
The three parameter names, from, to, and total, all are prepended with #. On line 154,
the parameter names are used as external parameter names once again to call the function,
and the use of those names clearly shows what the functions purpose and parameter order
is: a check written from Bart Stewart to Alan Laeur for a total of $101.
func writeBestCheck(#from : String, #to : String, #total : Double) -> String {
return "Check payable from \(from) to \(to) for $\(total)"
}

writeBestCheck(from : "Bart Stewart", to: "Alan Lafleur", total : 101.0)

THE FUNCTION 103


FIGURE 4.17 When
external param-
eter names are not
necessary

TO USE OR NOT TO USE?


External parameter names bring clarity to functions, but they also require more typing on
the part of the caller who uses your functions. Since they are optional parts of a functions
declaration, when should you use them?
In general, if the function in question can benet from additional clarity of having exter-
nal parameter names provided for each parameter, by all means use them. The check writing
example is such a case. Avoid parameter ambiguity in the cases where it might exist. On the
other hand, if youre creating a function that just adds two numbers (see lines 156 through
160 in Figure 4.17), external parameter names add little to nothing of value for the caller.
func addTwoNumbers(number1 : Double, number2 : Double) -> Double {
return number1 + number2
}

addTwoNumbers(33.1, 12.2)

104 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.18 Assigning
a value to a parameter
results in an error.

DONT CHANGE MY PARAMETERS!


Functions are prohibited from changing the values of parameters passed to them, because
parameters are passed as constants and not variables. Consider the function cashCheck
onlines 162 through 169 in Figure 4.18.
func cashCheck(#from : String, #to : String, #total : Double) -> String {
if to == "Cash" {
to = from
}
return "Check payable from \(from) to \(to) for $\(total) has been cashed"
}

cashCheck(from: "Jason Guillory", to: "Cash", total: 103.00)

The function takes the same parameters as our earlier check writing function: who the
check is from, who the check is to, and the total. On line 163, the to variable is checked for the
value "Cash" and if it is equal, it is reassigned the contents of the variable from. The rationale
here is that if you are writing a check to Cash, youre essentially writing it to yourself.

THE FUNCTION 105


FIGURE 4.19
A potential work-
around to the param-
eter change problem

Notice the error: Cannot assign to let value to. Swift is saying that the parameter to is
a constant, and since constants cannot change their values once assigned, this is prohibited
and results in an error.
To get around this error, you could create a temporary variable, as done in Figure 4.19.
Here, a new variable named otherTo is declared on line 163 and assigned to the to variable,
and then possibly to the from variable assuming the condition on line 164 is met. This is
clearly acceptable and works ne for our purposes, but Swift gives you a better way.
With a var declaration on a parameter, you can tell Swift the parameter is intended to be
variable and can change within the function. All you need to do is add the keyword before
the parameter name (or external parameter name in case you have one of those). Figure 4.20
shows a second function, cashBetterCheck, which declares the to parameter as a variable
parameter. Now the code inside the function can modify the to variable without receiving
an error from Swift, and the output is identical to the workaround function above it.

106 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.20 Using
variable parameters to
allow modifications

func cashBetterCheck(#from : String, var #to : String, #total : Double) ->


p String {
if to == "Cash" {
to = from
}
return "Check payable from \(from) to \(to) for $\(total) has been cashed"
}

cashBetterCheck(from: "Ray Daigle", to: "Cash", total: 103.00)

THE FUNCTION 107


FIGURE 4.21 Using
the inout keyword to
establish a modifiable
parameter

THE INS AND OUTS


As youve just seen, a function can be declared to modify the contents of one or more of its
passed variables. The modication happens inside the function itself, and the change is not
reected back to the caller.
Sometimes having a function change the value of a passed parameter so that its new value
is reected back to the caller is desirable. For example, in the cashBetterCheck function on
lines 172 through 177, having the caller know that the to variable has changed to a new value
would be advantageous. Right now, that functions modication of the variable is not reected
back to the caller. Lets see how to do this in Figure 4.21 using Swifts inout keyword.
func cashBestCheck(#from : String, inout #to : String, #total : Double) ->
p String {
if to == "Cash" {
to = from
}
return "Check payable from \(from) to \(to) for $\(total) has been cashed"
}

108 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


var payer = "James Perry"
var payee = "Cash"
println(payee)
cashBestCheck(from: payer, to: &payee, total: 103.00)

println(payee)

Lines 181 through 186 dene the cashBestCheck function, which is virtually identical to
the cashBetterCheck function on line 172, except the second parameter to is no longer a
variable parameterthe var keyword has been replaced with the inout keyword. This new
keyword tells Swift the parameters value can be expected to change in the function and that
the change should be reected back to the caller. With that exception, everything else is the
same between the cashBetterCheck and cashBestCheck functions.
On lines 188 and 189, two variables are declared: payer and payee, with both being
assigned String values. This is done because inout parameters must be passed a variable.
Aconstant value will not work, because constants cannot be modied.
On line 190, the payee variable is printed, and the Results sidebar for that line clearly
shows the variables contents as "Cash". This is to make clear that the variable is set to its
original value on line 189.
On line 191, we call the cashBestCheck function. Unlike the call to cashBetterCheck on
line 179, we are passing variables instead of constants for the to and from parameters. More
so, for the second parameter (payee), we are prepending the ampersand character (&) to the
variable name. This is a direct result of declaring the parameter in cashBestCheck as an
inout parameter. You are in essence telling Swift that this variable is an in-out variable and
that you expect it to be modied once control is returned from the called function.
On line 193, the payee variable is again printed. This time, the contents of that variable do
not match what was printed on line 189 earlier. Instead, payee is now set to the value "James
Perry", which is a direct result of the assignment in the cashBestCheck function on line 183.

BRINGING CLOSURE
Functions are great, and in the earlier code youve written, you can see just how versa-
tile they can be for encapsulating functionality and ideas. Although the many contrived
examples you went through may not give you a full appreciation of how useful they can be
in every scenario, that will change as you proceed through the book. Functions are going to
appear over and over again both here and in your coding, so understand them well. You may
want to re-read this chapter to retain all the ins and outs of functions.
Weve got a little more to talk about before we close this chapter, however. Our tour of
functions would not be complete without talking about another signicant and related
feature of functions in Swift: closures.

BRINGING CLOSURE 109


In laymans terms, a closure is essentially a block of code, like a function, which closes
in or encapsulates all the state around it. All variables and constants declared and
dened before a closure are captured in that closure. In essence, a closure preserves the
state of the program at the point that it is created.
Computer science folk have another word for closures: lambdas. In fact, the very notion
of the function you have been working with throughout this chapter is actually a special
case of a closurea function is a closure with a name.
So if functions are actually special types of closures, then why use closures? Its a fair
question, and the answer can be summed up this way: Closures allow you to write simple
and quick code blocks that can be passed around just like functions, but without the over-
head of naming them.
In essence, they are anonymous blocks of executable code.
Swift closures have the following structure:
{ (parameters) -> return_type in
statements
}

This almost looks like a function, except that the keyword func and the name is missing;
the curly braces encompass the entire closure; and the keyword in follows the return type.
Lets see closures in action. Figure 4.22 shows a closure being dened on lines 196 through
201. The closure is being assigned to a constant named simpleInterestCalculationClosure.
The closure takes three parameters: loanAmount, interestRate (both Double types), and
years(an Int type). The code computes the future value of a loan over the term and returns it
as aDouble.
// Closures
let simpleInterestCalculationClosure = { (loanAmount : Double, var
p interestRate : Double, years : Int) -> Double in
interestRate = interestRate / 100.0
var interest = Double(years) * interestRate * loanAmount

return loanAmount + interest


}

func loanCalculator(loanAmount : Double, interestRate : Double, years :


p Int, calculator : (Double, Double, Int) -> Double) -> Double {
let totalPayout = calculator(loanAmount, interestRate, years)
return totalPayout
}

var simple = loanCalculator(10_000, 3.875, 5, simpleInterestCalculationClosure)

110 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


FIGURE 4.22 Using
a closure to compute
simple interest

The formula for simple interest calculation is:


futureValue = presentValue * interestRate * years
Lines 203 through 206 contain the function loanCalculator, which takes four param-
eters: The same three that the closure takes, and an additional parameter, calculator,
which is a closure that takes two Double types and an Int type and returns a Double type.
Not coincidentally, this is the same parameter and return type signature as our previously
dened closure.
On line 208, the function is called with four parameters. The fourth parameter is the
constant simpleInterestCalculationClosure, which will be used by the function to com-
pute the total loan amount.
This example becomes more interesting when you create a second closure to pass to the
loanCalculator function. Since youve computed simple interest, then write a closure that
computes the future value of money using the compound interest formula:
futureValue = presentValue (1 + interestRate)years

BRINGING CLOSURE 111


FIGURE 4.23 Adding
a second closure that
computes compound
interest

Figure 4.23 shows the compound interest calculation closure dened on lines 210
through 215, which takes the exact same parameters as the simple calculation closure on line
196. On line 217, the loanCalculator function is again called with the same parameters as
before, except the compoundInterestCalculationClosure is passed as the fourth parameter.
As you can see in the Results sidebar, compound interest yields a higher future value of the
loan than simple interest does.
let compoundInterestCalculationClosure = { (loanAmount : Double,
p var interestRate : Double, years : Int) -> Double in
interestRate = interestRate / 100.0
var compoundMultiplier = pow(1.0 + interestRate, Double(years))

return loanAmount * compoundMultiplier


}

var compound = loanCalculator(10_000, 3.875, 5, compoundInterest


p CalculationClosure)

112 CHAPTER 4 WRITING FUNCTIONS AND CLOSURES


On line 212 you may notice something new: a reference to a function named pow. This
is the power function, and is part of Swifts math package. The function takes two Double
parameters: the value to be raised and the power to raise it to. It returns the result as a
Double value.

SUMMING IT UP
Weve spent the entire chapter discussing functions and their use. Toward the end, you
learned about closures and how they are essentially nameless functions that can be passed
around to do useful work. As I indicated earlier, functions and closures are the founda-
tions on which Swift apps are written. They appear everywhere and are an integral part of
the development process. Knowing how they work and when to use them is a skill you will
acquire over time.
In fact, there are even more things about functions and closures that I didnt touch on in
this chapter. Theres no need to overload you on every possible feature they have; well cover
those extras later in the book. For now, you have enough of the basics to start doing useful
programming.
Also, feel free to work with the code in the playground for this chapter. Change it, modify
it, add to it, and make a mess of it if you want. Thats what playgrounds are for, after all!

STAY CLASSY
With functions and closures covered, well turn our attention to the concept of the class. If
you are familiar with object-oriented programming (OOP), Swifts notion of a class is similar
to that of Objective-C and C++. If youre new to the idea of objects and OOP, dont worry,
well explain all that terminology in the next chapter.
Meanwhile, feel free to take a break and review the notes and code in this chapter, as well
as experiment with your playground le. When youre ready, proceed to Chapter 5, and well
get down and dirty with classes.

STAY CLASSY 113


This page intentionally left blank
INDEX

SYMBOLS
+ (addition), performing, 21 append method, adding, 165
&& (ampersands), using with logical AND, 261 append() method, using with arrays, 36, 3839
[ ] (brackets), using with arrays, 37 ARC (automatic reference counting), 251
: (colon), using with arrays, 37 array index, explained, 35
, (comma), using with arrays, 34 array iteration, 5254
/ (division), performing, 21 array values
== (double equal), using in comparisons, 68 inserting, 4041
! (exclamation) point removing, 3940
explained, 188, 197 replacing, 3940
using with logical NOT, 260 arrays. See also empty arrays
> (greater-than) symbol, eect of, 69 accessing elements in, 36
< (less-than) symbol, eect of, 69 adding values to, 36
* (multiplication), performing, 21 of arrays, 4850
# (pound) sign, prepending to parameter combining, 4142
names, 103 conrming values in, 35
? (question mark), using with Int declaring to hold type values, 37
declarations, 43 dened, 34
(subtraction), performing, 21 versus dictionaries, 42, 48, 50
(three periods), using with for-in loop, extending, 3839
5860 using colon (:) with, 37
_ (underscore), using, 168 using commas with, 34
| | (vertical bar), using with logical OR, 261 attributes, explained, 116
Attributes inspector, using in Xcode, 226
A
account balances, adding, 8990 B
account tuple, example of, 93 balances, nding, 9192
actions and outlets, connecting, 190191 bank account, depositing check into, 9293
addition (+) bank balances, nding, 9192
and multiplication code, 266267 base class, modeling, 129132
performing, 21 Bash shell, 269
administrator password, entering, 9 behaviors, explained, 116
aliases, using, 27 binary notation, 23
ampersands (&&), using with logical AND, 261 Bonjour, monde, 10
AND operator, using, 261 Bool variable type, 15, 2425
API Reference, accessing, 274 brackets ([ ]), using with arrays, 37
App Delegate object, using, 190 break keyword, using, 81
AppDelegate.swift source le, 178179, 187

INDEX 279
breakpoints explained, 117
creating, 207 expressing objects with, 117
encountering, 208, 256 names, 117
in MailCheckers deinit method, 258 properties, 117
setting, 207 versus protocols, 150153
bugs using, 119120
encountering, 206 using in code, 252
xing, 209210 in Xcode, 186189
identifying, 209 close method, calling, 120
locating, 206 closures
setting breakpoints, 207210 for computing compound interest, 112
buttonClicked action method, 189 for computing simple interest, 110111
buttons cycles in, 257259
creating for FollowMe UI, 225227 example, 110
creating in Xcode, 182 explained, 110
selecting in Xcode, 226 functions as, 110
as reference types, 257
C using in code, 252
using in extensions, 167168
Calculate button, clicking, 189, 191
using with games, 240
Calculate Simple button, creating, 203
Cocoa framework, 220
CamelCase, explained, 59
formatter, 194
candy jar example. See also collections
returning optionals in, 196
array values, 37
Cocoa Touch
combining arrays, 4142
playerLoses method, 242
error, 36
playerWins method, 242
explained, 34
UIAlertView class, 242
extending arrays, 3839
CocoaConf, attending, 277
inserting values, 4041
code, inspecting, 7880
let keyword, 34
code samples, running, 7
removing values, 3940
code snippets, speed limit, 78
replacing values, 3940
coding in real time, 7
case keyword, using with enumerations, 142
ColaMachine class, extending, 162
cashBestCheck function, dening, 109
collections, iterating, 5255. See also candy jar
cashCheck function, 105
example
casting values, 13
colon (:), using with arrays, 37
Character variable type, 15
CombinationDoor class
building Strings from, 20
creating, 135137
using, 20
testing, 138
check writing function, 100101
comma (,), using with arrays, 34
class keyword, dening objects with, 119
Command-click shortcut, using, 274
class methods, dening, 119
comparing
class relationship, 128
numbers, 59
classes
strings, 70
deriving from superclasses, 128
values and constants, 68
elements of, 117

280 INDEX
compilation process, starting in Xcode, 180 dictionary iteration, 5455
compound interest calculation division (/), performing, 21
correcting, 210 Document outline button, clicking, 190
performing, 112 documentation, accessing, 274
reviewing, 201 dollars property, adding, 196
testing, 205207 door, locking and unlocking, 121124
compound interest class, adding, 202203 Door class, instantiating, 120
computed properties. See also properties Door object, 118119
explained, 164 dot notation
using, 197 using with methods, 121
concatenating strings, 19 using with properties, 121
conferences, attending, 277 using with tuples, 28
constants double equal (==), using in comparisons, 68
comparing, 68 Double type, extending, 194196
declaring explicitly, 18 double value, explained, 12
using, 1314 Double variable type, 15
and variables, 14 do-while loop, using, 7677
constraints, setting for FollowMe game,
228230 E
Continue program execution button, 256
else clause, executing, 68
convenience initializers, using, 139141
empty arrays, declaring, 51. See also arrays
currency format, showing, 197
empty dictionaries, creating, 5152.
Seealsodictionaries
D enumerations
data, grouping with tuples, 2829 creating and using, 142144
Debug area icon, identifying, 255 explained, 141
declaration, explained, 1011 using case keyword with, 142
declaring, variables, 11 using in FollowMe game, 236
default keyword, using, 73 equal versus identical, 267268
delegation, using with protocols, 158161 equality
description method, using, 189 operations, 69
design patterns, 230 testing for, 80
designated initializer, explained, 139140 error messages, immutable value type, 36
dictionaries. See also empty dictionaries errors
adding entries, 45 details of, 12
versus arrays, 42, 48, 50 disappearance of, 231
creating, 4243 displaying, 231
keys and values, 42 exclamation (!) point
looking up entries in, 4345 explained, 188, 197
ordering, 43 with logical NOT, 260
removing entries, 47 extending types
returning tuples, 55 gigabytes, 163164
Scoville units, 4244 megabytes, 163164
updating entries, 46

INDEX 281
extensions increment operation, 62
explained, 162 initialization, 61
form of, 162 modication, 6162
using with Int type, 163 for-in loop
external parameters. See also parameters; as enumeration mechanism, 58
shorthand external parameter naming requirements, 58
best practices, 104 use of three periods (.), 5860
using with functions, 100103 formatter class, using in Cocoa, 194
fractions, mixing with numbers, 22
F frontDoor object, opening and closing, 120
functions
false, returning, 24
calling, 8687
Finder window, opening, 8
as closures, 110
Float variable type, 15
coding, 8485
oating point number, explained, 1112
conversion formula, 86
FollowMe game. See also gameplay;
creating, 88
iOSsimulator; Simon game;
declaring, 85
storyboarding
explained, 84
building UI for, 224
external parameters, 100, 102
class, 236
as rst-class objects, 9294
coding, 231235
indicating start of, 85
creating project for, 222223
versus methods, 117
enumerations, 236
nesting, 9698
linking buttons to method, 246
parts of, 84
model objects, 237
returning functions, 9496
overridable methods, 238
using default parameters in, 99100
playing, 247
variable parameter passing in, 89
playSequence method, 244
variadic parameter, 90
Product Name, 223
randomButton method, 244
randomness, 243 G
running in iOS simulator, 227 game methods
setting constraints, 228230 advanceGame, 242
Single View Application template, 223 animateWithDuration method, 239
starting, 244 animation parameters, 240
Tag property for red button, 245 buttonByColor, 238239
view objects, 236237 buttonByColor method, 239
winning and losing, 242244 closures, 240
FollowMe user interface colorTouched constant, 241
Auto Layout, 224 for FollowMe game, 238242
buttons, 225227 highlightColor variable, 239
Main.storyboard le, 224 highlightTime parameter, 240
for loop if statement, 239
addition and subtraction, 62 optional chaining, 241
evaluation, 61 originalColor variable, 239
exibility, 61 playSequence() method, 239

282 INDEX
recursion, 240 inheritance
switch/case construct, 238 base class, 129132
tag properties for UIButtons, 241 class relationship, 128
type method, 239 enumerations, 141144
variable declarations, 239 explained, 128
gameplay. See also FollowMe game; initializers, 139141
Simongame instantiating subclasses, 133139
elements, 221 structures, 144145
losing, 221 subclasses, 132133
play ow, 221 using with protocols, 157158
playability, 221 value types versus reference types, 145147
randomness, 221 init method
winning, 221 calling for superclass, 133
generic methods. See also methods creating, 125126
exercising, 264 as designated initializer, 139140
explained, 263 for NiceDoor class, 133
syntax, 263 initializers. See convenience initializers
<T> placeholder, 263 inout keyword, using with modiable
Go menu, displaying, 8 parameter, 108
greater-than (>) symbol, eect of, 69 insert() method, using with arrays, 41
grouping data with tuples, 2829 inspector icons, using in Xcode, 225
instantiating subclasses, 133139
H instantiation, explained, 119
Int type, extending, 163164
Hello World! , 10
Int* variable type, 15
:help command, typing at prompt, 10
integers
hexadecimal notation, 23
positive and negative, 15
HUD (heads-up display) window, using in
testing for equality, 267
Xcode, 190191
interactivity, benets of, 7
inverse function, declaring, 87
I iOS
IDE (integrated development environment), MVC (model-view-controller), 230
components of, 174 versus OS X, 220
identical versus equal, 267268 iOS Developer Program, joining, 276
if clause, encountering, 67 iOS simulator, launching, 227. See also
if statement FollowMe game
explained, 66 iPhones, aspect ratio, 222
predicate, 66 iterating collections, 5255
wrapping in for loop, 71
if/then/else clause K
explained, 66
keyboard shortcuts, using, 274
form of, 67
kilobyte (kb), converting Int to, 163164
import keyword, using in Xcode, 179
import statement, displaying in playground
window, 65

INDEX 283
L value versus reference, 250251
weak reference, 256
labels, creating in Xcode, 183
methods versus functions, 117. See also
large number notation, 23
generic methods
lazy property, example of, 257. See also
mobile platform. See iOS
properties
model objects, using in FollowMe game, 237
leniency, using in Xcode, 201
modiable parameter, using inout keyword
less-than (<) symbol, eect of, 69
with, 108. See also parameters
let keyword
modulo (%) operation, performing, 21
changing to var keyword, 125, 127
multiplication (*), performing, 21
using, 1314
mutable array
using with candy jar, 34
example of, 38
Letter class, creating, 253254
explained, 36
LLVM compiler, 250
mutating method, using in Int class, 165167
loanCalculator function, calling, 112
MVC (model-view-controller), 230
lock function, declaring, 152
MyFirstSwiftAppTests.swift source le, 212
logical NOT operator, using, 260
logical operations
AND, 259261 N
code sample, 262 name, entering, 9
combining with logical AND, 261 negative numbers, implying, 21
indicating, 261 nested functions, using, 9698
NOT, 259260 newBackDoor object, changing color of, 127
OR, 259261 newDoor object, instantiating, 126
loops, exiting from, 81 newFrontDoor object, properties of, 124
NewLockUnlockProtocol, creating, 154155
M NiceDoor class
adding, 132
Mac Developer Program, joining, 276
instantiating, 134135
MacTech Conference, attending, 277
NiceWindow class
MailBox class, creating, 253254
adding, 132
Main.storyboard le, using with FollowMe,
dening, 133
224
instantiating, 134
math functions, notation for, 84
nil
mathematical expressions, 2122
explained, 29
megabyte (mb), converting Int to, 163164
using, 196
memory address, explained, 250
NOT operator, using, 260
memory management
notications, using in Xcode, 179
breakpoint, 256
NSNumberFormatter class, explained, 194
Letter class, 253254
NSNumberFormatter object, using, 199200
LLVM compiler, 250
number formatter, Lenient option, 201
MailBox class, 253254
numbers, comparing, 59
MailChecker object, 258
numeric representations
reference count, 251
binary, 23
retain/release model, 251
hexadecimal, 23
test code, 254256
large number notation, 23

284 INDEX
octal, 23 password, entering, 9
scientic notation, 23 playground window
numeric types, mixing, 22 code and code results, 65
comments, 65
O default code in, 65
import statement, 65
object tree, displaying in Xcode, 201
panes in, 65
Objective-C development conferences,
Results sidebar, 65
attending, 277
variable declaration, 65
objects
playgrounds
dening with class keyword, 119
benets, 65
expressing via classes, 117
conventions, 65
identifying, 116
creating, 64
instantiating, 119
explained, 64
testing identity of, 268269
inspecting code in, 7880
octal notation, 23
naming, 64
online communities, joining, 276
Portal class
OOP (object-oriented programming). See also
adding, 129130
Swift programming language
adjusting with name property, 131
explained, 116
positive numbers, implying, 21
inheritance, 128
post increment, explained, 63
open method, calling, 120
pound (#) sign, prepending to parameter
operators
names, 103
overloading, 265266
predicate, using with if statement, 66
using, 6970
prepend method, adding, 165
optional chaining, using with games, 241
print method, explained, 10, 2627
optionals
printIn method, using, 1011, 13, 2627
declaring types as, 30
program ow, explained, 66
declaring variables as, 30
properties, explained, 116. See also computed
explained, 29, 197
properties; lazy property
implicitly unwrapped, 188
protocols
returning, 196
applying multiple, 155156
unwrapping, 188
versus classes, 150153
using in Xcode, 188
creating functions for, 156
Option-click shortcut, using, 274275
and delegation, 158161
OR operator, using, 261
and inheritance, 157158
OS X versus iOS, 220
using, 153155
outlets and actions, connecting, 190191
Push Button UI element, creating in
override keyword, using, 137
Xcode,182

P Q
parameter values, retaining, 105
question mark (?), using with Int
parameters, using with functions, 100. See also
declarations, 43
external parameters; modiable parameter;
:quit command, typing, 10
shorthand external parameter naming

INDEX 285
R signed integers, 15
Simon game. See also FollowMe game;
$R3 temporary variable, 25
gameplay
randomness, achieving in games, 243
described, 220
real time, coding in, 7
UI design, 221222
recursion, using with games, 240
simple interest calculator. See also computed
reference count, explained, 251
properties; Xcode IDE
reference cycle
adding result label, 185
breaking, 256258
buttonClicked action method, 189
explained, 252
buttons, 182
placement in AppDelegate.swift, 255
Calculate button, 191
reference types versus value types, 145147,
compounding, 201206
250251
formatted input, 200
regression, explained, 211
inputs, 180181
removeAtIndex() array method, using, 39
interest rate eld, 198201
REPL (Read-Eval-Print-Loop) environment, 7.
labels, 183
See also Swift REPL
loan amount eld, 198201
REPL, restarting from Terminal, 35
optimizing window size, 185
REPL commands, built-in help for, 10
outputs, 180181
Results sidebar, icons in, 80
renaming button title, 184
testing, 185
S text elds, 184
safety, emphasis on, 36 UI (user interface), 182184
scientic notation, 23 using, 111, 203
Scoville units, 4244 speed limit code snippet, 78
scripting. See shell scripts Spotlight, using, 8
securityDoor object, instantiating, 137 Step Over icon, using, 210
self keyword, using, 126 stepping over lines, 208
shell scripts storyboarding
arguments parameter, 273 FollowMe game, 245246
creating under Xcode, 270 in Xcode, 224
editing, 270271 String type, extending, 165
execute method, 272273 String variable type, 15
Execution class, 272, 274 building from Character type, 20
explained, 269 concatenating, 19
hash bang, 272 using toInt() method with, 17
import statement, 272 strings
running, 272 comparing, 70
setting permissions, 271 testing equality of, 25
type method, 273 structures
writing, 270 explained, 144
shorthand external parameter naming, using, 144147
explained, 103. See also external subclasses
parameters; parameters creating, 132133
instantiating, 133139

286 INDEX
subtraction () performing, 21 type promotion, explained, 22
superclass, explained, 128 types. See variable types
Swift programming language. See also OOP
(object-oriented programming) U
interacting with, 7
UI (user interface)
running code samples, 7
building in Xcode, 181184
Swift REPL, starting, 9. See also REPL
connecting actions to, 189190
(Read-Eval-Print-Loop) environment
connecting outlets to, 189190
switch statement, using, 7275
UIButton object
switch-case statement, using, 7275
tag property for, 241
using in Cocoa Touch, 225
T UIKit frameworks, importing, 231, 236
temperature conversion, performing, 8587 UInt* variable type, 15
temperature units, computing, 164 unary operators, using, 21
temporary variables. See also variable types underscore (_), using, 168
assigning values to, 25 unit tests. See also tests
creating, 106 framework, 213
Terminal application performing, 211212
nding, 8 unlock function, declaring, 152
launching, 8 unlock method, using, 138
test methods, variables used with, 214 unsigned integers, 15
tests. See also unit tests
failure of, 215216 V
passing, 214
value types versus reference types, 145147,
running, 214, 216217
250251
writing, 212214
values
text elds, using in Xcode, 184
comparing, 68
three periods () using with for-in loop,
displaying, 13
5860
var declaration, using on parameter, 106
Timeline pane, accessing, 80
var keyword
Tractor class
changing let keyword to, 125, 127
convenience initializers in, 139
using, 11
using, 141
variable declaration, displaying in
trac light analogy, setting up, 67
playground,65
tuples
variable modication, reecting to caller,
grouping data with, 2829
108109
returning for dictionaries, 55
variable parameters, using, 106107
type alias, explained, 27
variable types. See also temporary variables;
type conversion, explained, 17. See also
type conversion
variable types
adding .max to, 16
type method
adding .min to, 16
in games, 239
Bool, 15, 2425
in shell scripts, 273
Character, 15

INDEX 287
variable types (continued) X
declaring explicitly, 18
Xcode 6, requirement of, 7
Double, 15
Xcode IDE. See also simple interest calculator
explained, 14
AppDelegate.swift source le, 178179
Float, 15
Attributes inspector, 226
Int*, 15
attributes inspector, 200
interaction between, 16
classes, 186189, 198
limits, 1516
clues about source code, 178
String, 15
comments, 178
UInt*, 15
components of, 174
variables
context-sensitive help, 198
adding to protocol denitions, 153
creating user interface, 181184
assigning types to, 12
debug area, 177
assigning values to, 12
debug process, 209
comparing, 267
Document outline button, 190
and constants, 14
editor area, 177178, 188
declaring, 11
le creation dialog, 186
declaring as implicitly unwrapped
File menu, 175
optionals, 188
le template, 186
declaring as optionals, 30
Help menu, 275
names, 13
HUD (heads-up display) window, 190191
parameter passing notation, 8990
import keyword, 179
usefulness of, 13
initializing applications, 178
variadic parameter, explained, 90
input leniency, 201
VendingMachineProtocol, dening, 161
inspector icons, 225
vertical bar (| |), using with logical OR, 261
iOS project group, 175
view objects, using in FollowMe game,
keyboard shortcuts, 198
236237
labels, 183
ViewController.swift le, using, 231
maximizing workspace, 182
Void keyword, explained, 98
methods, 198
navigator area, 176178
W notications, 179
weak reference, explained, 256 NsNumberFormatter object, 199200
while loop object tree, 201
do-while variation, 7677 optimizing window size, 185
form of, 7576 optionals, 188
stopping, 81 Option-click shortcut, 275
using, 76 OS X project group, 175176
writeCheck function, 99101 project options, 176

288 INDEX
project save dialog, 176
project templates, 175
project window, 176180
Push Button UI element, 182
releases of, 174
selecting buttons in, 226
starting compilation process, 180
storyboarding, 224
target setup, 177
toolbar, 176
utilities area, 177
Xcode IDEdebug process, executing control
over, 209
XIB le, contents of, 190

INDEX 289

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy