<<

Professional Swift™

I ntroduction...... xxiii

▸▸ Part i Building Applications with Swift Ca h pter 1 A Swift Primer...... 3 Ca h pter 2 Writing a Swift Program ...... 35 Ca h pter 3 Classes, Structs, and Enums...... 61 Ca h pter 4 Concurrency in Swift...... 81 Ca h pter 5 Interfacing with Web Services...... 95 Ca h pter 6 Storing Data with Core Data...... 119

▸▸ Part Ii advanced Swift Concepts Ca h pter 7 Extending Classes...... 149 Ca h pter 8 Advanced Data Types ...... 167 Ca h pter 9 Bridging Swift and Objective‐ ...... 189 Ca h pter 10 Debugging Swift Applications ...... 207 Ca h pter 11 The Swift Runtime...... 229 App endix An Overview of C...... 247

I ndex...... 265

Por fessional S wift™

Por fessional S wift™

Michael Dippery Professional Swift™ Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2015 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-119-01677-9 ISBN: 978-1-119-14872-2 (ebk)

ISBN: 978-1-119-14871-5 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro- motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub- lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http:// booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2015937849 Trademarks: Wiley, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or regis- tered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Swift is a trademark of Apple, Inc. All other trademarks are the property of their respec- tive owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book. To Jean Gold, for encouraging me to put pen to paper in the first place.

Ab out the Author

Michael Dippery is a software developer for Industrial Light & Magic in San Francisco, CA. A graduate of Bucknell University’s computer science program, he has also worked for SocialCode in San Francisco and The New York Review of Books in New York. While most of his day is spent writing Python code, he has long been fond of Objective‐C. He has contributed to both the Adium and Colloquy projects on OS X and has written and released numerous open source libraries for Objective‐C. When he’s not working in Objective‐C, Michael is just crazy enough to enjoy writing code in Haskell and Erlang. He looks forward to the potential for Swift to improve software devel- opment on iOS and OS X. Outside of programming, Michael enjoys reading, writing fiction, and taking photographs with one of his many cameras.

C redits

A cquisitions Editor Professional Technology & Strategy Aaron Black Director Barry Pruett Project Editor Maureen Tullis Business Manager Amy Knies T echnical Editor Chaim Krause A ssociate Publisher Jim Minatel Production Editor Dassi Zeidel Project Coordinator, Cover Brent Savage C opy Editor Nancy Rapoport Proofreader Rebecca Rider Manager of Content Development & Assembly I ndexer Mary Beth Wakefield Johnna VanHoose Dinse

Marketing Director C over Designer David Mayhew Wiley

Marketing Manager C mover I age Carrie Sherrill ©iStock.com/OJO_Images

A cknowledgments

T hanks to My parents, Steven and Kim, for never wavering in their support of my education and career, even though they’ve never fully understood what it is I do. Liza Veloz, for giving me my first opportunities as both a technical writer and a programmer. Professor Luiz Felipe Perrone, for taking me under his wing and providing valuable mentoring and friendship over the last ten years. Mary James, for inviting me to write a book in the first place.

Contents

Introduction xxiii

Part I: Building Applications with Swift

Cha pter 1: A Swift Primer 3

What Is Swift? 4 Why Learn Swift? 5 Working with Constants and Variables 5 Understanding Swift Data Types 6 Using Numerical Types 6 Boolean Types 7 Using Character Types 8 Using Arrays 10 Using Dictionaries 10 Using Tuples 11 Working with Type Annotations 12 Minimizing Annotation with Type Inference 13 Clarifying Code with Type Aliasing 14 Working with Operators 15 Using Basic Operators 15 Using Compound Assignment Operators 17 Using Overflow Operators 17 Using Range Operators 18 Using Logical Operators 18 Using Comparison Operators 19 Using Custom Operators 19 Making Decisions with Control Flow 19 Using Conditional Statements 20 Using Loops 23 Control Transfer Statements 25 Grouping Types with Enumerations 26 Working with Functions 27 Declaring Functions 27 Specifying Parameter Names 28 Defining Default Parameters 29 Ces ont nt

Specifying Variadic Parameters 29 Specifying Constant, Variable, and In-Out Parameters 30 Function Types 31 Using Closures 32 Summary 34

Cha pter 2: Writing a Swift Program 35

Setting Up Xcode 36 Downloading from Apple’s Developer Portal 36 Downloading Xcode 36 Experimenting with Playgrounds 38 Using Playgrounds in Xcode 38 A Simple Example in Playground 38 A More Exciting Playground Example 40 Writing Swift in Xcode 41 Creating a New Swift Project 42 Creating the Swiftisms App 44 Creating the Interface 45 Creating Connections between the View Controller and the Object 46 Connecting the Buttons and the Action 50 Displaying Random Strings 51 What Next? 53 Debugging Swift Applications 53 Understanding Breakpoint Types 54 Setting Breakpoints 54 Using the Debugger 55 Using the Hierarchical View 56 Using the Debugger View and the po Command 56 Executing the Program 58 Summary 59

Cha pter 3: Classes, Structs, and Enums 61

Working with Classes and Structs 62 Defining Classes and Structs 62 Initializing Classes and Structs 64 Creating an Initial Value 64 Defining Your Own Initializer 65 Writing an Initializer 66 Working with Multiple Initializers 68 Deinitializing Classes 69 xvi coes nt nt

Working with Properties 70 Using Simple Properties 70 Using Lazy Properties 72 Using Computed Properties 72 Observing Property Changes 73 Understanding Methods 74 Understanding the Difference between Classes and Structs 76 Working with Enumerations 78 Summary 79 Cha pter 4: Concurrency in Swift 81

What Is Concurrency? 82 Understanding Processes 82 Understanding Threads 84 Why Concurrency? 85 Designing Concurrent Programs 85 Concurrency in iOS and OS X 86 Understanding Event Loops 86 Understanding Run Loops 87 Understanding Asynchronous Methods 87 Understanding NSTimer 89 Understanding NSThread 91 Understanding Grand Central Dispatch 92 Summary 94 Cha pter 5: Interfacing with Web Services 95

Understanding Web Services 95 Implementing a Web Services Client 97 Signing Up for a Firebase Account 97 Laying Out the User Interface 98 Hooking Up the Add Album View Controller 101 Adding the Album Creation View Controller 103 Hooking Up the Segue 104 Creating the Album Model 104 Communicating with Firebase 106 Creating the Firebase Connector 106 Making Asynchronous Web Requests 109 Processing JSON Data 110 Creating New Albums 111 Deleting Albums 112 Wiring Up the View and Data Models 112

xvii Ces ont nt

Wiring Up the Segue 115 Run the Application 116 Summary 118

Cha pter 6: Storing Data with Core Data 119

What Is Core Data? 120 The Core Data Stack 120 Using Core Data with Swift 121 Setting Up the Birthdays Application 122 Getting User Input 128 Examining Xcode Files 129 Adding Methods to the AppDelegate Class 134 Handling the Dialog Sheet 135 Hooking Up the Dialog Sheet 137 Displaying Data 137 Implementing the Table View’s Behavior 138 The Completed Application Delegate 140 Summary 145

Part II: Advanced Swift Concepts

Cha pter 7: Extending Classes 149

Working with Class Extensions 150 Adding Methods to Classes 150 Adding Properties to Classes 152 Mutating Classes in Extensions 153 Specifying Behavior with Protocols 153 Adopting Protocols 154 Declaring Properties and Methods 154 Working with Optional Methods and Properties 156 Protocols Are Types 158 Checking for Protocol Conformance 158 Using Protocol Types in Collections 159 Composing Protocols 160 Inheriting from Other Protocols 160 Adopting Protocols in Class Extensions 161 Working with Generics 163 Generic Classes 164 Working with Type Constraints 165 Summary 166

xviii coes nt nt

Cha pter 8: Advanced Data Types 167

Working with Enums and Algebraic Data Types 168 Matching Patterns 168 Putting It All Together with JSON 170 Working with Optional Types 172 Working with Null Values 172 Excluding Null Values 173 Understanding Swift’s Version of Null 173 Chaining Optional Values 174 Understanding Type Casting 175 Grouping Values with Tuples 177 Custom Operators 179 Defining Custom Operators 183 Defining Precedence and Associativity 183 A Final Word about Operators 186 Using Functions and Closures 187 Summary 188

Cha pter 9: Bridging Swift and Objective‐C 189

The Successor to Objective-C 190 Introducing Namespaces and Modules 191 Organizing Code with Namespaces 191 Distributing Code with Modules 193 Using Access Modifiers 193 Specifying an Access Level 194 How Swift and Objective-C Interact 194 Using Swift Classes in Objective-C 195 Generating an Objective-C Header 195 Objective-C and Swift-Only Features 196 Using Swift Code in an Objective-C Application 196 Using Objective-C in Swift 198 Generating a Bridging Header 198 Calling Objective-C Code from Swift 199 Using C and C++ Code with Swift 202 Working with C Scalar Types 202 Accessing Memory with C Pointers 203 Working with Global Constants and Defines and Swift 204 Calling C Code from Swift 204 Using C++ Code in Swift 206 Summary 206

xix Ces ont nt

Cha pter 10: Debugging Swift Applications 207

The Art of Debugging 208 Creating CircleView 208 Drawing the Circle 209 Adding Sliders 210 Completing the Project 211 Printing Values 213 Working with Debuggers 215 Examining Errors with lldb, the LLVM Debugger 216 Basic Breakpoints 216 Using lldb to Inspect Programs 218 Using the Variable Pane 218 Entering Commands in the lldb Command Prompt Pane 218 Displaying Code Hierarchy with the lldb Ribbon 219 Walking through a Program with the lldb Ribbon 221 Removing or Disabling Breakpoints 222 Setting Conditional Breakpoints 222 Setting Symbolic Breakpoints 223 Exploring the Debugger 225 Summary 228 Cha pter 11: The Swift Runtime 229

What Is a Runtime? 230 Understanding the Objective‐C Runtime 231 Dispatching Methods Dynamically in Objective‐C 231 Message Passing 233 Resolving Methods 233 Messages and Methods 237 Exploring the Swift Runtime 238 Understanding Virtual Method Tables 239 Loading Swift Programs 241 Summary 245 App endix: An Overview of c 247

Comparing Procedural and Object-Oriented Programming Styles 248 Understanding the Importance of C Language Syntax 249 Defining Data with Variables and Arrays 249 Integral Data Types 249 Floating-Point Data Types 251 Arrays 252

xx coes nt nt

Typedefs 253 Enums 254 Performing Calculations with Operators 254 Arithmetic Operators 254 Logical Operators 256 Relational Operators 258 Bitwise Operators 258 Bitshift Operators 259 Referencing Data with Pointers 260 Organizing Data with Structs 261 Generalizing Data with Unions 261 Referencing Functions with Function Pointers 262

Index 265

xxi

Introduction

T he popularity of iOS has drawn many programmers to Apple’s platforms. Software on both OS X and iOS has long been written in Objective‐C, a language first developed in the 1980s that is best described as an amalgamation of C and . Objective‐C lacks many features that modern programmers expect to find in a . Over the last ten years, Apple has adapted and improved Objective‐C, but many programmers still find it to be an alien language. Enter Swift. Swift is a modern programming language, built with knowledge gained in the last 30 years of programming language research. Developed by the same researchers who developed clang, the modern compiler toolchain used by Apple to build OS X and iOS software, Swift incorporates many features that are expected of a modern programming language. It sports a strong to prevent many of the mistakes prevalent in both C and Objective‐C programming. It has a refined class system complete with static and computable properties. It supports closures and treats func- tions as first‐class objects, allowing them to easily be saved as variables or passed to functions and methods as parameters. As you read this book, you’ll find many more advanced features that are present in Swift as well. Swift has been designed from the ground up to be a modern programming language suitable for both systems and application development on Apple’s platforms. Apple has already thrown a lot of support behind Swift, and the language is constantly being improved. Swift represents the future of software development on iOS and OS X, and programmers working on that platform should expect Swift to occupy an increasingly dominant position on those systems.

Whos Thi Book Is For

This book is aimed at software developers with experience writing Objective‐C applications on OS X or iOS. Some knowledge and experience with Swift are recommended but are by no means necessary to understand the material presented in this book. The book introduces the key concepts of Swift that may be new even to advanced iOS and OS X programmers. Over the course of the book, several small projects are used to illustrate the concepts as they are introduced. The text also makes extensive use of playgrounds, a new feature of Xcode that allows you to write and interact with Swift code without the overhead of an entire Xcode project. The first chapter is an overview of Swift’s syntax and semantics but does not cover any advanced features of the language. The second chapter covers the use of Xcode, including playgrounds. If you already have some familiarity with Swift and Xcode, you may want to skip the first and second chapters and get started immediately with Chapter 3. introduction

Whats Thi Book Covers

This book first offers a primer to the Swift programming language, released by Apple in June 2014. It quickly moves on to more advanced Swift programming topics, including the new playgrounds feature in Xcode; classes, structs, and enums; concurrent programming; and advanced features of Swift’s type system. It also covers practical topics that you will deal with on a regular basis as a Swift programmer, including interfacing with web services using JSON, Core Data, and using C and Objective‐C code in your Swift project. It shows some of the advanced features of Xcode, includ- ing the use of the debugger built in to Xcode, and discusses the lower‐level details of the Swift and Objective‐C runtimes. And because it is impossible to completely avoid C when writing software on OS X and iOS, an index provides a quick overview of the C programming language. Swift has been constantly evolving since its release in June 2014. This book covers version 1.1. Because Swift is still changing, you may find some minor differences between the version discussed in this book and the latest released version. However, the vast majority of material presented in this book will still be valid for future versions of Swift.

Hs ow Thi Book Is Structured

This book is divided into two sections. The first section provides an introduction to the Swift programming language and covers many of the more practical topics you will encounter as a Swift programmer. The second section is a “deep dive” into the intricacies of Swift. ➤➤ Chapter 1: Reviews the syntax and semantics of the Swift programming language. It is useful for those programmers who are new to the language or want a quick refresher. ➤➤ Chapter 2: Covers the Swift‐related changes to Xcode. It introduces Xcode’s new feature, playgrounds, which provide a way to interactively work with Swift code. ➤➤ Chapter 3: Covers Swift’s classes, structs, and enums in greater detail than Chapter 1, providing a solid foundation for object‐oriented programming in Swift. ➤➤ Chapter 4: Discusses concurrent programming in the context of Swift and the Foundation framework on iOS and OS X. ➤➤ Chapter 5: Shows you how to communicate with remote web services using JSON. ➤➤ Chapter 6: Discusses how to use Core Data to store and search for information used by your program. ➤➤ Chapter 7: Shows you how to extend classes using protocols and class extensions. ➤➤ Chapter 8: Covers Swift’s type system in fine detail and shows you how to take advantage of Swift’s strong type system to write less error‐prone code. ➤➤ Chapter 9: Shows you how you can mix C and Objective‐C code in your Swift programs.

xxiv introduction

➤➤ Chapter 10: Introduces the debugger and shows you how you can track down and fix problems in your code. ➤➤ Chapter 11: Discusses the runtime architecture of both Swift and Objective‐C and demon- strates how programs are loaded and executed on iOS and OS X. ➤➤ Appendix: Covers the features and concepts that the C programming language introduces.

If you are already familiar with Swift and Xcode, you may want to skip Chapters 1 and 2 and start right in on Chapter 3.

What You Need to Use This Book

To run the samples in the book, you will need the following: ➤➤ A Mac running OS X 10.9 or later ➤➤ Xcode 6 ➤➤ An iPhone, iPod Touch, or iPad if you want to run the examples on an actual device instead of the iOS simulator that ships with Xcode

The source code for the samples is available for download from the Wrox website at: www.wrox .com/go/proswift.

C onventions

To help you get the most from the text and keep track of what’s happening, this book uses a number of conventions.

W ArnING Warnings hold important, not‐to‐be‐forgotten information that is directly relevant to the surrounding text.

N ote Notes indicate notes, tips, hints, tricks, or asides to the current discussion.

As for styles in the text: ➤➤ We highlight new terms and important words when we introduce them. ➤➤ We show keyboard strokes like this: Ctrl+A.

xxv introduction

➤➤ We show file names, URLs, and code within the text like so:persistence.properties . We present code in two different ways: We use a monofont type with no highlighting for most code examples. We use bold to emphasize code that is particularly important in the present context or to show changes from a previous code snippet.

Source Code

As you work through the examples in this book, you may choose either to type in all the code man- ually or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com. Specifically for this book, the code download is on the Download Code tab at www.wrox.com/go/proswift.

You can also search for the book at www.wrox.com by ISBN (the ISBN for this book is 978‐1‐119‐01677‐9) to find the code. And a complete list of code downloads for all current Wrox books is available at www.wrox.com/dynamic/books/download.aspx. At the beginning of each chapter, we’ve provided a list of the major code files for the chapter. Throughout each chapter, you’ll also find references to the names of code files as needed in listing titles and text.

Most of the code on www.wrox.com is compressed in a .ZIP, .RAR, or similar archive format appropriate to the platform. Once you download the code, just decompress it with an appropriate compression tool.

N ote Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978‐1‐119‐01677‐9.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download .aspx to see the code available for this book and all other Wrox books.

E rrata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.

To find the errata page for this book, go towww.wrox.com/go/proswift , and click the Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. xxvi introduction

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/ techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book. p2p. wrox.com

For author and peer discussion, join the P2P forums at http://p2p.wrox.com. The forums are a Web‐based system to which you can post messages relating to Wrox books and related technologies and where you can interact with other readers and technology users. The forums offer a subscription feature to e‐mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com, you will find a number of different forums that will help you, not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps: 1. Go to http://p2p.wrox.com and click the Register link. 2. Read the terms of use and click Agree. 3. Complete the required information to join, as well as any optional information you wish to provide, and click Submit. 4. You will receive an e‐mail with information describing how to verify your account and com- plete the joining process.

N ote You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e‐mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

xxvii