Swift Development with Cocoa (2015)
We’ve been developing for the Cocoa framework since Mac first supported it. In that time, we’ve seen the ecosystem evolve from a small programming niche to one of the most important and influential development environments in the world. In our earlier books—which focused on Apple’s other programming language, Objective-C—with each revised edition, we’d boast about how Objective-C was climbing the language charts, hovering around the third most popular programming language in the TIOBE index.
We can’t yet boast that Swift, the language used in this book, has reached the top five languages (or even the top ten), but it’s definitely climbing the charts, and will almost certainly ascend to similarly lofty heights in the future.
When Apple announced Swift during its Worldwide Developers Conference (WWDC) in June 2014, we were amazed and quite excited. Because Apple keynotes take place in the middle of the night, Australian time, we hurriedly organized a 6 a.m. Skype meeting with our ever-patient editor, Rachel, and kicked off planning for this book. In the months that followed, we built a number of projects in Swift, to become familiar with the language and the way it was designed to be used.
Over the years, we’ve built a lot of large, complex iOS and OS X software, shipping it to millions upon millions of users along the way. We’ve picked up a deep understanding of the toolset, frameworks, and programming language—an understanding that is crucial to building the best possible software for iOS and OS X. Becoming familiar with the Swift way of doing things with Cocoa and Cocoa Touch was important, so we took a few months to work it all out. We wanted to make sure the book didn’t just explain Swift, but explained how to do things the right way with Swift and Cocoa/Cocoa Touch.
Apple constantly changes things, as evidenced by Swift, as well as the recent introduction of the powerful iPhone 6 and 6 Plus, and the ever-increasing power of iPads. This book will give you the knowledge, confidence, and appreciation for iOS and OS X development with Cocoa, Cocoa Touch, and Swift, and the current way things work.
Objective-C to Swift
The original Macintosh computers were mostly programmed in C, using a library called Toolbox. When Apple acquired NeXT Computer, Inc., and replaced its operating system with Mac OS X, Toolbox was replaced with Cocoa, which was written using the Objective-C programming language.
Objective-C was designed around the same time as its chief competitor, C++. Both languages are descendants of the C programming language, and are object-oriented programming languages. This means that, while C has separate functions and data structures, object-oriented languages like C++ and Objective-C combine related functions and data into objects. For example, an object named Car might contain information about its color, its speed, and the number of doors; it might also contain functions like drive, stop, and openDoor. This close connection of data to functions that work with that data lets you think about your software as a collection of modular tools, rather than thinking about the software as a single large entity.
Objective-C is a very powerful language. Its primary difference from C++ is that it is a dynamic language. In any object-oriented language, the binding of functions to the specific data that they work with needs to either happen when the code is compiled (static binding), or at runtime (dynamic binding). C++ uses static binding, which makes runtime performance faster, but reduces flexibility. Objective-C uses dynamic binding, which is slightly slower, but dramatically increases the flexibility of the language.
However, Objective-C has its own problems. Because it’s based on C, it inherited a number of quirks from its parent language, such as the preprocessor and pointer arithmetic (to name only a couple examples). These features, though powerful, tend to make code less readable and safe. Apple has done a good job of keeping the language up to date, but even die-hard fans of the language (which your humble authors consider themselves to be) see the language as getting a bit rusty.
This is where Swift comes in. Swift is a new language, designed to make programming iOS and Mac applications easier, faster, and safer. It’s designed to be easier to learn and more resilient to programmer error than Objective-C; indeed, Apple described it as “Objective-C without the C.” Because Swift is built and compiled with LLVM (the same toolset used by Objective-C), and uses the Objective-C runtime, you can write an app that uses C, Objective-C, and Swift.
Swift has a lot of very modern programming language features, including things like generics, type inference, type safety, closures, tuples, and automatic memory management. Swift is an evolving language, and will change over time, but it is the future of software development for Apple’s platforms! In this book, you’ll learn how to use Swift in real-world situations, and take advantage of the features in iOS and OS X to make your apps amazing.
This book is solely focused on Swift, and does not cover the use of Objective-C. We might mention it occasionally, but we don’t expect you to know how to use it.
We assume that you’re a reasonably capable programmer, but we don’t assume you’ve ever developed for iOS or OS X, or used Swift or Objective-C before. We assume that you’re fairly comfortable navigating OS X and iOS as a user, though.
Organization of This Book
In this book, we’ll be talking about Cocoa and Cocoa Touch, the frameworks used on OS X and iOS, respectively. Along the way, we’ll also be covering Swift, including its syntax and features.
Pretty much every chapter contains practical exercises that you can follow along with. The early chapters cover general topics, such as setting up a development environment and coming to grips with the Swift language, while later chapters cover specific features of Cocoa and Cocoa Touch.
Here is a concise breakdown of the material each chapter covers:
Chapter 1, Cocoa Development Tools
This chapter introduces Cocoa and Cocoa Touch, the frameworks used on OS X and iOS. It introduces Xcode, the integrated development environment (IDE) that you’ll be using while coding for these platforms. This chapter also covers the Apple Developer Programs, which are necessary if you want to distribute software on the Mac or iTunes App Stores.
Chapter 2, Programming with Swift
This chapter introduces and explores the Swift programming language, the features of the language, and the design patterns used for Swift development with Cocoa and Cocoa Touch. It also explores the basic data types (like strings, arrays, and dictionaries).
Chapter 3, Applications on OS X and iOS
This chapter discusses how applications are assembled and operate on Mac and iOS devices. In this chapter, we’ll talk about the application life cycle on both platforms, as well as how sandboxing affects application access to data and resources.
Chapter 4, Graphical User Interfaces
This chapter demonstrates how user interfaces are loaded and presented to the user. It introduces two of the most powerful concepts provided by Cocoa, nibs and storyboards, which are predesigned and preconfigured user interfaces, and which can be directly connected to your code. This chapter also touches on Core Animation, the animation system used on OS X and iOS, and UI Dynamics, used for adding physics to your user interfaces.
Chapter 5, Closures and Operation Queues
This chapter introduces closures, which are an incredibly powerful feature of the Swift language that allows you to store code in variables. Closures are functions that can be stored in variables and passed around like values. This makes things like callbacks very simple to implement. This chapter also introduces operation queues, which are a straightforward way to work with concurrency without having to deal with threads.
Chapter 6, Drawing Graphics in Views
In this chapter, you’ll learn about the drawing system used on both OS X and iOS, as well as how to draw custom graphics. We’ll also cover the Retina display, and how view geometry works.
Chapter 7, SpriteKit
This chapter explores SpriteKit, a framework available on both iOS and OS X that is designed for making fast and efficient 2D games and graphics.
Chapter 8, SceneKit
This chapter explores SceneKit, a framework available on both iOS and OS X that is designed for making fast and efficient 3D scenes and graphics. You’ll learn about materials, constraints, physics, camera, and lights.
Chapter 9, Audio and Video
This chapter covers audio and video playback using AVFoundation, the audio and video engine. You’ll also learn how to use speech synthesis, access the iOS photo library, and get access to the user’s photos.
Chapter 10, iCloud and Data Storage
This chapter covers a range of data storage options available on OS X and iOS. The filesystem, preferences, and iCloud are all covered. In addition, you’ll learn how to make security-scoped bookmarks, which allow sandboxed apps to retain access to locations that the user has granted your apps permission to use.
Chapter 11, Cocoa Bindings
This chapter covers Cocoa bindings, a tremendously powerful system that allows you to connect your application’s user interface to an application’s data without the need for intermediary glue code. Bindings are an OS X-only feature.
Chapter 12, Table Views and Collection Views
This chapter covers table views (an effective way to display multiple rows of data to your user) and collection views, which allow you to display a collection of items to the user.
Chapter 13, Document-Based Applications
This chapter discusses the document systems on both iOS and OS X, which are instrumental in creating applications that work with multiple documents. Here we discuss the differences in how the two platforms handle documents.
Chapter 14, Networking
Cocoa and Cocoa Touch provide straightforward tools for accessing networked resources, and this chapter demonstrates how to retrieve information from the Internet while keeping the application responsive. This chapter also covers the network service discovery system, Bonjour, and multipeer connectivity.
Chapter 15, Working with the Real World
This chapter covers a variety of technologies used to work with the physical world: Core Location, for getting access to the GPS; Core Motion, for learning about how the hardware is moving and oriented; and the printing systems on both iOS and OS X. Beacons, game controllers, and maps are also discussed.
Chapter 16, EventKit
This chapter discusses the calendaring system used on iOS and OS X, and demonstrates how to get access to the user’s calendar. We also discuss considerations for user privacy.
Chapter 17, Instruments and the Debugger
This chapter covers Instruments, the profiler and analysis tool for Mac and iOS applications. An example of a crashing application is discussed, and the cause of the crash is diagnosed and fixed using the application. Additionally, this chapter covers Xcode’s built-in debugger.
Chapter 18, Sharing and Notifications
This chapter discusses how applications can share text, images, and other content with various services like Twitter and Facebook, using the built-in sharing systems (which don’t require your application to deal with authenticating to these services). Additionally, we’ll cover both push notifications and local notifications, which allow your application to display information to the user without running.
Chapter 19, Nonstandard Apps
Not every program you write will be an app that sits on the user’s home screen, and this chapter tells you how to write four different kinds of nontraditional apps: command-line tools, menu bar apps, multiscreen iOS apps, and preference panes.
Chapter 20, Working with Text
This chapter covers TextKit, as well as the string localization system available on iOS and OS X. Here we also discuss data extraction from text using the built-in data detectors.
Conventions Used in This Book
The following typographical conventions are used in this book:
Indicates new terms, URLs, email addresses, filenames, and file extensions.
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.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.