




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
guide to program for iphone and ipad
Typology: Study Guides, Projects, Research
1 / 620
This page cannot be seen from the preview
Don't miss anything!
Covers
(^) iOS 10,
Xcode 8, and Swift 3
ISBN: 978-1-491-97007-
[LSI]
iOS 10 Programming Fundamentals with Swift, Third Edition by Matt Neuburg
Copyright © 2017 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Rachel Roumeliotis Production Editor: Kristen Brown Proofreader: O’Reilly Production Services Indexer: Matt Neuburg
Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Matt Neuburg
April 2015: First Edition October 2015: Second Edition October 2016: Third Edition
Revision History for the Third Edition 2016-09-23: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781491970072 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 10 Programming Fundamentals with Swift, the image of a harp seal, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
iii
Table of Contents | v
vi | Table of Contents
viii | Table of Contents
Preface
On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐ ment: “We have a new programming language.” This came as a huge surprise to the developer community, which was accustomed to Objective-C, warts and all, and doubted that Apple could ever possibly relieve them from the weight of its venerable legacy. The developer community, it appeared, had been wrong.
Having picked themselves up off the floor, developers immediately began to examine this new language — Swift — studying it, critiquing it, and deciding whether to use it. My own first move was to translate all my existing iOS apps into Swift; this was enough to convince me that, for all its faults, Swift deserved to be adopted by new students of iOS programming, and that my books, therefore, should henceforth assume that readers are using Swift.
The Swift language is designed from the ground up with these salient features:
Object-orientation Swift is a modern, object-oriented language. It is purely object-oriented: “Every‐ thing is an object.”
Clarity Swift is easy to read and easy to write. Its syntax is clear, consistent, and explicit, with few hidden shortcuts and minimal syntactic trickery.
Safety Swift enforces strong typing to ensure that it knows, and that you know, what the type of every object reference is at every moment.
Economy Swift is a fairly small language, providing some basic types and functionalities and no more. The rest must be provided by your code, or by libraries of code that you use — such as Cocoa.
xi
Memory management Swift manages memory automatically. You will rarely have to concern yourself with memory management.
Cocoa compatibility The Cocoa APIs are written in C and Objective-C. Swift is explicitly designed to interface with most of the Cocoa APIs.
These features make Swift an excellent language for learning to program iOS.
The alternative, Objective-C, still exists, and you can use it if you like. Indeed, it is easy to write an app that includes both Swift code and Objective-C code; and you may have reason to do so. Objective-C, however, lacks the very advantages that Swift offers. Objective-C agglomerates object-oriented features onto C. It is therefore only partially object-oriented; it has both objects and scalar data types, and its objects have to be slotted into one particular C data type (pointers). Its syntax can be difficult and tricky; reading and writing nested method calls can make one’s eyes glaze over, and it invites hacky habits such as implicit nil-testing. Its type checking can be and fre‐ quently is turned off, resulting in programmer errors where a message is sent to the wrong type of object and the program crashes. It uses manual memory management; the recent introduction of ARC (automatic reference counting) has alleviated some of the programmer tedium and has greatly reduced the likelihood of programmer error, but errors are still possible, and memory management ultimately remains manual.
Recent revisions and additions to Objective-C — ARC, synthesis and autosynthesis, improved literal array and dictionary syntax, blocks — have made it easier and more convenient, but such patches have also made the language even larger and possibly even more confusing. Because Objective-C must encompass C, there are limits to how far it can be extended and revised. Swift, on the other hand, is a clean start. If you were to dream of completely revising Objective-C to create a better Objective-C, Swift might be what you would dream of. It puts a modern, rational front end between you and the Cocoa Objective-C APIs.
Therefore, Swift is the programming language used throughout this book. Neverthe‐ less, the reader will also need some awareness of Objective-C (including C). The Foundation and Cocoa APIs, the built-in commands with which your code must interact in order to make anything happen on an iOS device, are still written in C and Objective-C. In order to interact with them, you have to know what those languages would expect. For example, in order to pass a Swift array where an NSArray is expected, you need to know what constitutes an object acceptable as an element of an Objective-C NSArray.
Therefore, in this edition, although I do not attempt to teach Objective-C, I do describe it in enough detail to allow you to read it when you encounter it in the docu‐ mentation and on the Internet, and I occasionally show some Objective-C code.
xii | Preface
aspects of the language that, in my experience, actually come into play in the course of programming iOS.
The reader of this book will thus get a thorough grounding in the fundamental knowledge and techniques that any good iOS programmer needs. The book itself doesn’t show how to write any particularly interesting iOS apps, but it does constantly use my own real apps and real programming situations to illustrate and motivate its explanations. And then you’ll be ready for Programming iOS 10, of course!
Versions
This book is geared to Swift 3, iOS 10, and Xcode 8.
In general, only very minimal attention is given to earlier versions of iOS and Xcode. It is not my intention to embrace in this book any detailed knowledge about earlier versions of the software, which is, after all, readily and compendiously available in my earlier books. The book does contain, nevertheless, a few words of advice about back‐ ward compatibility (especially in Chapter 9).
xiv | Preface
The Swift language included with Xcode 8, Swift 3, has changed very significantly from its predecessor, Swift 2. A few important basic syntax changes were foreshad‐ owed in Swift 2.2 and Swift 2.3, but Swift 3 adds many more, plus “renamification” has changed the names of many standard library and Cocoa methods, along with the new Foundation “overlay” that removes the “NS” prefix from certain type names. Fortunately, if you have existing Swift 2 code, Xcode 8 comes with a migrator that will update your Swift 2 code to Swift 3 in a remarkably intelligent fashion. This book, conversely, is totally incompatible with Swift 2 and doesn’t discuss it; for the most part, I behave as if Swift 2 never existed. I do call out a few particularly noteworthy Swift 3 innovations, but by no means all of them.
In this edition, I have dropped my earlier convention of referring to Cocoa methods by their Objective-C name, because “renamification” has made it impossible to deduce the Swift 3 name of an Objective-C method. Instead, I give the name in Swift, as a function reference (as described in Chapter 2) — that is, the name plus the parameter labels followed by colon in parentheses. Now and then, if a method is already under discussion and there is no ambiguity, I’ll use the bare name. (In a few places, such as Appendix A, where the Objective-C language is explicitly under dis‐ cussion, I naturally do still use Objective-C method names.)
Please bear in mind that Apple continues to make adjustments to the Swift language. I have tried to keep my code up-to-date right up to the moment when the manuscript left my hands; but if, at some future time, a new version of Xcode is released along with a new version of Swift, some of the code in this book, and even some informa‐ tion about Swift itself, might be slightly incorrect. Please make allowances, and be prepared to compensate.
Screenshots of Xcode were taken using Xcode 8 under OS X 10.11 El Capitan. I have not upgraded my machine to macOS 10.12 Sierra, because at the time of this writing it was too new to be trusted with mission-critical work. If you are braver than I am and are running Sierra, your interface may naturally look very slightly different from the screenshots, but this difference will be minimal and shouldn’t cause any confu‐ sion.
Acknowledgments
My thanks go first and foremost to the people at O’Reilly Media who have made writ‐ ing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown, Dan Fauxsmith, Adam Witwer, and Sanders Kleinfeld come particularly to mind. And let’s not forget my first and long-standing editor, Brian Jepson, whose influence is present throughout.
Preface | xv
The widespread eagerness to program iOS, however, though delightful on the one hand, has also fostered a certain tendency to try to run without first learning to walk. iOS gives the programmer mighty powers that can seem as limitless as imagination itself, but it also has fundamentals. I often see questions online from programmers who are evidently deep into the creation of some interesting app, but who are stymied in a way that reveals quite clearly that they are unfamiliar with the basics of the very world in which they are so happily cavorting.
It is this state of affairs that has motivated me to write this book, which is intended to ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to write about it, but it is iOS and its popularity that has given me a proximate excuse to do so. Here I have attempted to marshal and expound, in what I hope is a pedagogi‐ cally helpful and instructive yet ruthlessly Euclidean and logical order, the principles and elements on which sound iOS programming rests. My hope, as with my previous books, is that you will both read this book cover to cover (learning something new often enough to keep you turning the pages) and keep it by you as a handy reference.
This book is not intended to disparage Apple’s own documentation and example projects. They are wonderful resources and have become more wonderful as time goes on. I have depended heavily on them in the preparation of this book. But I also find that they don’t fulfill the same function as a reasoned, ordered presentation of the facts. The online documentation must make assumptions as to how much you already know; it can’t guarantee that you’ll approach it in a given order. And online documentation is more suitable to reference than to instruction. A fully written example, no matter how well commented, is difficult to follow; it demonstrates, but it does not teach.
A book, on the other hand, has numbered chapters and sequential pages; I can assume you know views before you know view controllers for the simple reason that Part I precedes Part II. And along with facts, I also bring to the table a degree of expe‐ rience, which I try to communicate to you. Throughout this book you’ll find me referring to “common beginner mistakes”; in most cases, these are mistakes that I have made myself, in addition to seeing others make them. I try to tell you what the pitfalls are because I assume that, in the course of things, you will otherwise fall into them just as naturally as I did as I was learning. You’ll also see me construct many examples piece by piece or extract and explain just one tiny portion of a larger app. It is not a massive finished program that teaches programming, but an exposition of the thought process that developed that program. It is this thought process, more than anything else, that I hope you will gain from reading this book.
Conventions Used in This Book
The following typographical conventions are used in this book:
Preface | xvii
Italic Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords.
Constant width bold Shows commands or other text that should be typed literally by the user.
Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available for download at http://github.com/mattneub/Programming-iOS-Book-Examples.
This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “iOS 10 Programming Fundamentals with Swift by Matt Neuburg (O’Reilly). Copyright 2017 Matt Neuburg, 978-1-491-97007-2.”
xviii | Preface