Preface

With the arrival of Swift 5 in early 2019, the stamp of maturity has been placed upon the Swift language. When Swift was introduced to the public in 2014, it was a sort of second-class citizen. The Cocoa frameworks that give an iOS app its functionality expect to be spoken to in Objective-C, and several megabytes of libraries had to be included in every Swift app, effectively containing the whole of the Swift language and translating everything into Objective-C. But Swift 5 introduces ABI stability, which means that, starting in iOS 10.2, the Swift language has become part of the system. Swift is now on a par with Objective-C, and Swift apps are smaller and faster.

When Swift first appeared, I immediately translated my own existing iOS apps into Swift, and found them easier to understand and maintain than their Objective-C originals. Objective-C is a powerful language with some remarkable capabilities, but it is safe to say that the vast majority of new iOS programmers will adopt Swift. It is a superb language to learn, even (perhaps especially) if you’ve never programmed before, and is the easiest and clearest way to program iOS. Swift has these salient features:

Object-orientation

Swift is a modern, object-oriented language. It is purely object-oriented: “Everything 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.

Memory management

Swift manages memory automatically. You will rarely have to concern yourself with memory management.

Cocoa compatibility

The Cocoa APIs are written primarily in C and Objective-C. Swift is explicitly designed to interface with most of the Cocoa APIs.

Even when your code is in Swift, some awareness of Objective-C (including C) can be useful. The Foundation and Cocoa APIs are still written in C and Objective-C. In order to interact with them, you might have to know what those languages would expect. Therefore in this book I describe Objective-C in enough detail to allow you to read it when you encounter it in the documentation and on the internet, and I occasionally show some Objective-C code. Part III, on Cocoa, is largely about learning to think the way Objective-C thinks — because the structure and behavior of the Cocoa APIs are fundamentally based on Objective-C. And the book ends with an appendix that details how Swift and Objective-C communicate with one another, as well as explaining how your app can be written partly in Swift and partly in Objective-C.

The Scope of This Book

This book is intended to accompany and precede Programming iOS 13, which picks up where this book leaves off. If writing an iOS program is like building a house of bricks, this book teaches you what a brick is and how to handle it, while Programming iOS 13 shows you some actual bricks and tells you how to assemble them.

When you have read this book, you’ll know about Swift, Xcode, and the underpinnings of the Cocoa framework, and you will be ready to proceed directly to Programming iOS 13. Conversely, Programming iOS 13 assumes a knowledge of this book; it begins, like Homer’s Iliad, in the middle of the story, with the reader jumping with all four feet into views and view controllers, and with a knowledge of the language and the Xcode IDE already presupposed. If you started reading Programming iOS 13 and wondered about such unexplained matters as Swift language basics, the UIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delegation and notification, and retain cycles, wonder no longer — I didn’t explain them there because I do explain them here.

This book 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, as it teaches you the underlying basis of iOS programming. It has three parts:

  • Part I introduces the Swift language, from the ground up — I do not assume that you know any other programming languages. My way of teaching Swift is different from other treatments, such as Apple’s; it is systematic and Euclidean, with pedagogical building blocks piled on one another in what I regard as the most helpful order. At the same time, I have tried to confine myself to the essentials. Swift is not a big language, but it has some subtle and unusual corners that you probably don’t need to know about. Also, I never mention Swift playgrounds or the REPL. My focus here is real-life iOS programming, and my explanation of Swift concentrates on the practical aspects of the language that actually come into play in the course of programming iOS.

  • Part II turns to Xcode, the world in which all iOS programming ultimately takes place. It explains what an Xcode project is and how it is transformed into an app, and how to work comfortably and nimbly with Xcode to consult the documentation and to write, navigate, and debug code, as well as how to bring your app through the subsequent stages of running on a device and submission to the App Store. There is also a chapter on nibs and the nib editor (Interface Builder), including outlets and actions as well as the mechanics of nib loading (but such specialized topics as autolayout constraints in the nib are postponed to the other book).

  • Part III introduces the Cocoa Touch framework. The Foundation and UIKit frameworks, and other frameworks that they entail, constitute Cocoa, which provides the underlying functionality that any iOS app needs to have. To use a framework effectively, you have to think the way the framework thinks, put your code where the framework expects it, and fulfill many obligations imposed on you by the framework. Also, Cocoa uses Objective-C, so you need to know how your Swift code will interface with Cocoa’s features and behaviors. Cocoa provides important foundational classes and adds linguistic and architectural devices such as categories, protocols, delegation, and notifications, as well as the pervasive responsibilities of memory management. Key–value coding and key–value observing are also discussed here.

    The last chapter of Part III is about the general problem of how objects can refer to one another in an iOS program. In addition to the traditional Cocoa-based solutions, I also discuss the new Swift Combine framework. Also, in June of 2019, Apple introduced SwiftUI. It constitutes an alternative to UIKit and Cocoa, with a completely different programming paradigm for constructing apps. I do not teach SwiftUI in this book — that would require another entire book — but I do explain its chief linguistic features, and I talk about its solutions to the problem of communicating between objects within an iOS app and how they differ from Cocoa patterns.

From the Programming iOS 4 Preface

The popularity of the iPhone, with its largely free or very inexpensive apps, and the subsequent popularity of the iPad, have brought and will continue to bring into the fold many new programmers who see programming for these devices as worthwhile and doable, even though they may not have felt the same way about OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their emphasis shifted from OS X to iOS instruction.

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. Here I have attempted to marshal and expound, in what I hope is a pedagogically 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 experience, 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.

Versions

This book is geared to Swift 5.1, iOS 13, and Xcode 11.

In general, only very minimal attention is given to earlier versions of iOS and Xcode. Earlier versions can be very different from the current version, and it would be impossible to go into detail about all that has changed over the years. Besides, that information is readily and compendiously available in my earlier books. Recent innovations are called out clearly. The book does contain some advice about backward compatibility (especially in Chapter 9).

I generally give method names in Swift, in the style of a function reference (as described in Chapter 2) — that is, the name plus parentheses containing the parameter labels followed by colon. 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 discussion, I use Objective-C method names.

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 information about Swift itself, might be slightly incorrect. Please make allowances, and be prepared to compensate.

Screenshots of Xcode were taken using Xcode 11 under macOS 10.14 Mojave. The interface on 10.15 Catalina is slightly different from the screenshots (especially if you’re using “dark mode”), but this difference will be minimal and shouldn’t cause any confusion.

Acknowledgments

This book was written with the aid of some wonderful software:

The book was typed and edited almost entirely on my faithful Unicomp Model M keyboard (http://pckeyboard.com).

At O’Reilly Media, many people have made writing this book fun and easy; particular thanks go to Kristen Brown, Rachel Roumeliotis, Dan Fauxsmith, Adam Witwer, Nick Adams, Heather Scherer, Melanie Yarbrough, Sarah Schneider, and Sanders Kleinfeld. My first editor was Brian Jepson; his influence is present throughout.

Finally, a special thanks to my beloved wife, Charlotte Wilson, for her sharp eye, her critical ear, and her unflagging encouragement. This book could not have been written without her.

Conventions Used in This Book

The following typographical conventions are used in this book:

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 elements 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 determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

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 significant 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 13 Programming Fundamentals with Swift by Matt Neuburg (O’Reilly). Copyright 2020 Matt Neuburg, 978-1-492-07453-3.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

O’Reilly Online Learning

Note

For almost 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their knowledge and expertise through books, articles, conferences, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, please visit http://oreilly.com.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/ios13-prog-fundamentals.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia