20,99 €
Get up and running with Swift--swiftly Brimming with expert advice and easy-to-follow instructions, Swift For Dummies shows new and existing programmers how to quickly port existing Objective-C applications into Swift and get into the swing of the new language like a pro. Designed from the ground up to be a simpler programming language, it's never been easier to get started creating apps for the iPhone or iPad, or applications for Mac OS X. Inside the book, you'll find out how to set up Xcode for a new Swift application, use operators, objects, and data types, and control program flow with conditional statements. You'll also get the scoop on creating new functions, statements, and declarations, learn useful patterns in an object-oriented environment, and take advantage of frameworks to speed your coding along. Plus, you'll find out how Swift does away with pointer variables and how to reference and dereference variables instead. * Set up a playground development environment for Mac, iPhone, iPad, and wearable computers * Move an existing Objective-C program to Swift * Take advantage of framework components and subcomponents * Create an app that uses location, mapping, and social media Whether you're an existing Objective-C programmer looking to port your code to Swift or you've never programmed for Apple in the past, this fun and friendly guide gets you up to speed swiftly.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 441
Veröffentlichungsjahr: 2015
Table of Contents
Cover
Title Page
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Beyond the Book
Where to Go from Here
Part I: Getting Started with Swift
Chapter 1: Setting Up an Xcode Swift Project
Looking Ahead to the End
Working with Swift
Getting the Developer Tools
Setting Up Your Mac
Planning Your Environment
Getting Started with Swift
Exploring Your Project
Chapter 2: Playing in the Playground
Creating a Playground
Using a Playground
Using the Timeline in the Playground
Chapter 3: Using the Xcode Editing Tools
Getting Started with Editing Tools
Completing Code with Code Completion
Using Fix-It to Correct Code
Folding and Unfolding Code
Using Code Snippets
Chapter 4: Creating a Swift App
Double-Checking Your Environment
Creating the Project
Testing the Template
Setting the Location for iOS Simulator
Adding the Map to the Storyboard and Project
Testing the App
Adding Swift Code to Locatapp
Testing the App with Location Data
Part II: Introducing Actions
Chapter 5: Operating on Data
Classifying Operators
Answering Syntax Questions with Playgrounds
Clearing the Way for Operators
Assigning Values with Assignment Operators
Counting On Arithmetic Operators for Math
Addition
Multiplication
Division
Incrementing and decrementing numeric values
Combining operators
Comparing values
Choosing and Checking Values with Logical Operators
Chapter 6: Using Swift Types
Understanding Types and Type Safety
Swift Standard Library Types
Specifying Variable or Expression Types with Type Annotations
Dealing with Tuples
Working with Optional Types
Using Generic Types
Chapter 7: Collecting Objects
Playing by Swift Collection Rules
Organizing Data Sequentially with Arrays
Organizing Data Logically with Dictionaries
Chapter 8: Controlling the Flow
Looping through Code
Using Conditions
Transferring Control
Using Assertions
Chapter 9: Functioning Successfully
Setting the Stage for the Social Media Location App
Exploring the Functions in Locatapp
Understanding the Locatapp Architecture
Uncovering the Function Features
Adding Location Support
Part III: Putting Expressions Together
Chapter 10: Expressing Yourself
Surveying the Types of Swift Expressions
Understanding Lazy Loading
Chapter 11: Declaring the Symbols
Navigating through Symbols with the Symbol Navigator
Preventing Disasters with Assertions
Patterns
Ranges
Chapter 12: Initializing and Deinitializing Data
Understanding Initialization
Performing Initialization
Understanding Deinitialization
Part IV: Using Components and Subcomponents
Chapter 13: Expanding Objects with Extensions
Working with a Swift Extension
Using Swift Extensions with a Built-In Class
Chapter 14: Managing Access Control for Your Objects
Introducing Access Control Levels
Using Swift Access Control Terminology
Chapter 15: Building Classes, Structures, and Enumerations
Exploring Classes, Structures, and Enumerations
Declaring a Simple Class
Exploring a Swift Class, Structure, or Enumeration File
Chapter 16: Using Properties, Variables, Outlets, and Actions
Understanding Properties and Variables
Encapsulating Data for Good Design and Maintainability
Understanding Properties and Variables in Locatapp
Declaring Outlets and Actions
Chapter 17: Working with Enumerations to Consolidate Values
Using Enumerations with Swift
Understanding Traditional C Structures and Enumerations
Exploring Swift Enumerations
Chapter 18: Using Protocols to Provide Templates for Functionality
Understanding Protocols
Experimenting with Protocols
Exploring Protocols and a UITableViewController
Chapter 19: Mixing Objective-C and Swift
Comparing Frameworks in Objective-C and Swift
Calling an Objective-C Method in Objective-C within Swift to Set a Pin on the Map
Bridging between Objective-C and Swift
Part V: The Part of Tens
Chapter 20: Ten Swift Features That Aren’t in Objective-C
Using Playgrounds to Explore Code and Syntax
Using Tuples
Using Ranges to Save Code
Taking Advantage of Strict Typing and Type Safety
Initializing Your Variables and Constants
Understanding Optional Types
Looking at Frameworks for Your Own Code
Including Annotations and Attributes in Declarations
Deinitializing Variables Where Necessary
Use Patterns to Simplify Your Code
Chapter 21: Ten Swift Features That Are Not in C
Strong Typing
Libraries Extend C
Switch Statements Fall through Cases in C
C Is an International Standard
Swift Is Tightly Linked to the Cocoa and Cocoa Touch Frameworks
Swift Includes Memory Management
Swift Is Designed to Function in a Multi-Threaded Environment
Types Can Be Created Easily in Swift
Swift Has Its Own IDE and Compiler
Types Can Be Classes, Structures, or Enumerations
Chapter 22: Ten Objective-C Features That Aren’t in Swift
Saying Goodbye to Header (.h) Files
Saying Farewell to Dangling Pointers (Almost Always)
Forgetting About Uninitialized Variables and Properties
Exploiting a Common Superclass Like
NSObject
Managing Type Casting
Preferring Closures to Blocks
Getting Rid of Legacy Memory Management
Replacing Property Decorators
Using Swift Style to Access Class Properties
Clarifying Swift Access Control
About the Author
Author’s Acknowledgments
Cheat Sheet
Advertisement Page
Connect with Dummies
End User License Agreement
Cover
Table of Contents
Begin Reading
i
ii
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
313
314
315
316
317
318
319
320
321
322
323
324
325
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
Swift™ For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2015 by John Wiley & Sons, Inc., Hoboken, New Jersey
Media and software compilation copyright © 2015 by John Wiley & Sons, Inc. All rights reserved.
Published simultaneously in Canada
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 the prior written permission of the Publisher. 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 www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Swift is a trademark of Apple, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book. Swift For Dummies® is an independent publication and has not been authorized, sponsored, or otherwise approved by Apple, Inc.
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 PROMOTIONAL 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 PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE 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 WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES 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 U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport.
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: 2014954655
ISBN 978-1-119-02222-0 (pbk); ISBN 978-1-119-02224-4(ebk); ISBN 978-1-119-02223-7 (ebk)
In June of 2014, one of the highlights of Apple’s Worldwide Developers Conference (WWDC) was the announcement — a surprise to many attendees, including the multitudes of developers watching the videos around the world — of the development of a new language aimed at developers to use with iOS and OS X devices. Called Swift, it was presented as the language of the future for Apple’s developers, but it was made very clear that it would cooperate with the existing basic development language — Objective-C. (In describing the ways Swift and Objective-C would interact, Apple repeatedly used the phrase “mix and match” — not only in the presentations at WWDC, but in other venues as well.)
Think about that date— Swift has only been around since June 2014: We’re all beginners with Swift.
Swift For Dummies is a beginner’s introduction to Apple’s new programming language. The book gets you started developing with Swift. You’ll quickly see how to create projects in Swift from the built-in templates that are part of the Xcode development tool. From there, you delve into the features of the language, from the basic to the advanced. Some of these features are unique to Swift whereas other, possibly more familiar features were inherited from other programming languages.
Before we get started with Swift, consider these two points:
Apple has done this before, and they know how to do it.
On both the hardware and software sides, Apple has successfully managed transitions to new technologies. Developers have sometimes cheered, sometimes booed, and even sometimes not even noticed much difference, but nonetheless, Apple has managed to bring them along to a new technology that makes their lives easier and improves things for users.
The languages are only part of the development environment for Apple.
When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language — either Objective-C or Swift. What differentiates the iOS and OS X development environment from most others is that the language is only one-third of the overall environment, as well as the fact that a single company (Apple) controls all of that environment.
Cocoa is the framework you use for developing Mac apps; Cocoa Touch is the framework for iOS apps. Both have a common heritage and many similar classes. In general, classes that start with NS are Cocoa classes, and classes that start with UI are Cocoa Touch classes. Many Cocoa NS classes are also used in Cocoa Touch, so you’ll find both types of classes in many of your apps and in the sample code and templates.
Code examples in this book appear in a monospaced font so that they stand out a bit better. Some non-syntax components appear in an italicized monospaced font. (Thus, weatherConditions might be a variable, but variable could be any variable you want to use.)
Like many languages, including Objective-C, Swift is case-sensitive, so please enter the code that appears in this book exactly as it appears in the text. I also use the standard Cocoa naming conventions — such as capitalizing class names and leaving the names of methods and instance variables lowercase.
Note that all URLs in this book appear in a monospaced font as well. In accordance with common usage, most URLs in this book include the subdomain (such as www) at the beginning of many URLs except for addresses that don’t require that component (such as developer.apple.com).
If you're ever uncertain about anything in the code, you can always look at the source code on my website at www.northcountryconsulting.com or the For Dummies website at www.dummies.com. From time to time, I’ll provide updates for the code there and post other things you might find useful.
This book makes few assumptions about readers because Swift programmers come from many backgrounds and with varying degrees of proficiency in various languages. As to the future, however, there’s one simple assumption: You want to create apps based on the Cocoa and Cocoa Touch frameworks, and you want to do it in the simplest way possible.
Fittingly, then, this book is aimed at Cocoa and Cocoa Touch developers at all stages of expertise, from those who’ve developed a multitude of App Store apps to those who have only thought about developing an app . . . someday.
I also assume you have some Mac or iOS experience. If you have never used a Mac or iOS device, you may find it hard to follow this book. I explain advanced technical terms as they arise, but my assumption is that you know, for example, what Settings (on iOS devices) and System Preferences (on Macs are), and that similar concepts are familiar to you.
You must have access to a Mac that can run the current version of Xcode (a free download from developer.apple.com). Without Xcode and the Mac to run it on, you can't experiment with the sample code.
Note that Xcode runs only on Macintosh computers running Mac OS X v10.9.4 (Mavericks) or later on a 64-bit Intel-based Mac.
Additionally, you must have Internet access. It’s very important to stress, however, that I don’t mean “always-on” Internet access. I only mean that you must at least have limited Internet access — so you can access the App Store, for example, and connect with Apple’s developer.apple.com to download software and upload apps.
Perhaps the most foolish assumption of all may be your own: that you can’t learn Swift or the Cocoa and Cocoa Touch frameworks. You can, and this book is designed to help you. Bear in mind that app development is not easy: If it were, the App Store would have far more than just over a million apps. It’s not easy, but you can do it.
This icon indicates a useful pointer that you shouldn't skip.
This icon represents a friendly reminder. It describes a vital point that you should keep in mind while proceeding through a particular section of the chapter.
This icon signifies that the accompanying explanation may be informative (dare we say interesting?), but it isn't essential to understanding Swift. Feel free to skip past these tidbits if you like (though skipping while learning may be tricky).
This icon alerts you to potential problems that you may encounter along the way. Read and obey these blurbs to avoid trouble.
A lot of extra content that you won’t find in this book is available at www.dummies.com. Go online to find the following:
Source code for the examples in this book at
www.dummies.com/extras/swift
This book contains a lot of code, and you might not want to type it. In fact, it’s probably better if you don’t type this code manually. Fortunately, you can find the source code for this book on the Dummies.com website at www.dummies.com/extras/swift. The source code is organized by chapter. The best way to work with a chapter is to download all the source code for it at one time.
Online articles covering additional topics at
www.dummies.com/extras/swift
Here you’ll find out how to know whether to use a type, collection, flow control, or function to implement an action; how to initialize stored properties in a class or structure; and how to let Xcode create actions and outlets for you.
Ongoing discussions at developer.apple.com (for registered developers only) and at my website (www.northcountryconsulting.com) provide even more information.
The Cheat Sheet for this book is at
www.dummies.com/cheatsheet/swift
Here you’ll find an examination of the anatomy of a Swift class, the best way to update Xcode for a new Swift release, and advice about working with both Swift and Objective-C.
Updates to this book, if we have any, are also available at
www.dummies.com/extras/swift
It’s time to start your Swift adventure! If you’re new to programming, start with Chapter 1 and progress through the book at a pace that allows you to absorb as much of the material as possible. If you’re in an absolute rush to get going with Swift as quickly as possible, you could possibly skip to Chapter 2 with the understanding that you may find some topics a bit confusing later.
Part I
Visit www.dummies.com for great For Dummies content online.
In this part . . .
Set up an Xcode Swift project.
Find out how to use a playground.
Explore the Xcode editing tools.
Write your first Swift app.
Chapter 1
In This Chapter
Introducing Swift
Setting up your computer for Swift
Defining your development preferences
Creating and exploring your first project
Swift is Apple’s new language for developers to use with iOS and OS X devices. As such, it is the successor to Apple’s existing iOS/OS X development language, Objective-C, but Swift has been designed to cooperate with and work alongside Objective-C, so this should be a slow transition to power.
Some Swift beginners come to the language with proficiency in other languages, ranging from C and its offshoots such as C++ and Objective-C, to newer languages such as Ruby, Python, and Java, as well as scripting languages such as PHP and JavaScript.
Whether you’re just starting out as an Apple developer or are an experienced developer who wants to add Swift to your skills, this chapter helps you get started. There’s one very important point to remember: As of this writing, the iOS API (application programming interface) and SDK (software development kit) are less than ten years old. (They were launched in early 2008, six months after the launch of iPhone.) The early years of iOS development were an exciting period as the pieces of today’s hardware and software environment fell into place. Only as thousands of developers and millions of users started actually using these devices and the languages that support them did some issues — bugs as well as great enhancements — begin to take shape.
Arguably, it took several years for the SDK to reach maturity. Many developers (including your humble author) believe that it was only with the release of iOS 4 in 2010 that the platform more or less stabilized as the operating system we recognize today. This was the first version to be called “iOS” rather than “iPhone OS,” and, with the release of iOS 4.2.1 in the fall of 2010, it was the first to support both iPhone and iPad. The first version of multitasking was present, and preparations were made for iCloud that was first released in iOS 5.
If you haven’t looked at iOS since that time, a lot has changed. The release of Swift and iOS 8 is a good opportunity to look around and get up to date with iOS (and, for that matter, OS X). This chapter helps you do that.
In this book, you’ll occasionally find warnings like this one about serious issues you should avoid. The warnings are used sparingly, so pay attention to them when they appear. The focus in this book is on getting you up and running as a Swift developer. That involves giving you the information you need as well as helping you along the way with encouragement and, from time to time, reminding you that you’re not the first person to learn Swift. Others have been there before, and, in most cases, others (most definitely including the author) have encountered the problems you may be facing. There are a multitude of warnings in this chapter. This isn’t intended to scare you off: Rather, it’s designed to help you over that first hump of becoming a Swift developer. After you have your first clean compile and have finished a build of a project (in the section, “Planning Your Environment,” later in this chapter), you’ll be on your way.
As you make progress in Swift, this book helps you build an app — a real, live app — based on one of the built-in Xcode templates. Sure, you're probably thinking, that’s just what I need — another “Hello World” app.
Actually, no. There’s no “Hello World” here. Instead, the app you’ll be building, called Locatapp, is a full-fledged Swift app created using the Master-Detail Application template that's built into Xcode, and it uses Cocoa Touch and a number of its frameworks to do its work. Locatapp uses location services on Cocoa Touch and the iOS mobile devices to find your location, as you see in Figure 1-1.
Figure 1-1: Locatapp finds your location.
If you prefer, you can download Locatapp from this book’s companion website, as described in the Introduction, but be warned — some of the details of registering as a developer described later in this chapter are needed to get Locatapp to run on your own device.
The pulsing blue dot shows your current location. Locatapp lets you store other locations you've visited. The latitude and longitude values of locations that have been visited are shown in the list at the left of Figure 1-1. Tap one of them, and you'll see a map with your current location and with the tapped location indicated by a red pin.
You can zoom in on the map (see Figure 1-2). This zoom-in functionality is all built into MapKit and the device so you don't have to write any code. As you zoom in, you can see that the two locations shown in Figure 1-1 are actually over 100 miles apart. The annotation for Current Location is also part of the framework.
Figure 1-2: Zooming the map.
In addition to the built-in annotation for Current Location, you can write your own annotations in Locatapp. Figure 1-3 shows a custom annotation that you'll write in the course of this book.
Figure 1-3: Writing your own annotations.
That action button at the right of the bar in the interface (the box with the arrow poking out of the top) is an interface element you can drag from the Xcode library into your user interface (called a storyboard). What happens when you tap that action button depends on a method you’ll build in this book. This method uses the built-in actions such as Messages, Mail, Twitter, Facebook, and so forth, as shown in Figure 1-4. (Yes, you'll write this code, but Cocoa Touch writes the supporting code to interact with Messages, Mail, Twitter, Facebook, and more.)
Figure 1-4: Implementing an action button.
Figure 1-5 shows a tweet you can construct in your app. Users can modify it (note that there are 57 characters left), but you write the code for the message and to insert the map coordinates. Note, too, that the image of a web page is part of the tweet. You'll see how to automatically put that into the tweet. Although you can tap the image of the web page all you want in this book, in Locatapp, tapping that image will take you to the web page in Safari.
Figure 1-5: Constructing social media messages from your code.
I’m sure you'll like Locatapp and enjoy thinking of ways you can build on it.
As I like to say, “Goodbye, ‘Hello World.’”
Apple has two annual calendars of events. Each is highlighted by one or more major announcements with periodic updates throughout the year. For consumers and end users, the annual calendar focuses on the releases of new and updated devices. As is true throughout the world of electronics, a large portion of annual sales occur during the summer and fall (“back-to-school”) and during the year-end holiday season.
On the software side, there is a related peak period. It’s no accident that Apple, Google, and Microsoft all hold conferences for their developers in May and June. Typically, they unveil the new features in their operating systems at that time, allowing developers a few months to work with those features before the peak period of hardware sales.
In June of 2014, one of the highlights of Apple’s Worldwide Developers Conference (WWDC) was the announcement — a surprise to many attendees — of a new development language for iOS and OS X devices. Called Swift, it was presented as the language of the future for Apple’s developers, but it was made very clear that it would co-operate with the existing basic development language — Objective-C.
This book gets you started developing with Swift. You’ll quickly see how to create projects in Swift from the built-in templates that are part of the Xcode development tool. From there, you’ll delve into features of the languages ranging from the basics to the advanced features that are unique to Swift as well as some features of Swift that may be familiar to you from other modern programming languages.
Swift and Objective-C are the languages most often used in building apps for iOS and OS X. Combined with the Cocoa (OS X) and Cocoa Touch (iOS) frameworks and Xcode, these languages allow you to develop just about anything you can dream of. It is hard to find an app that can’t be written with these tools: OS X and iOS apps as well as other Apple products such as Pages, Keynote, and Numbers are developed using Xcode and the Cocoa frameworks. Most of the language work for these products is in Objective-C or Swift, although some sections are still in C++. Apps developed with these technologies are native apps.
If you don’t want to go the native route, you can consider using other (non-Apple) frameworks. Three widely used frameworks are Titanium Appcelerator, PhoneGap, and HTML5, which is frequently used as a development tool without being a framework. In the world of Titanium Appcelerator, you typically write in JavaScript, whereas in PhoneGap you use Javascript, HTML, and CSS. HTML5, of course, is itself a language, which you can use in conjunction with JavaScript as well as other languages.
The advantages of using these non-native frameworks center around two features:
With these frameworks, the development process may be faster than the native-app framework.
Using these frameworks can help you develop cross-platform apps.
The biggest disadvantage is that non-native frameworks are third-party tools and as such aren’t guaranteed to support new (or even all current) features of Apple’s operating systems and hardware.
The cost of developing a native app for iOS, OS X, Android, or even Windows is likely to be significantly higher than that of using one of the tools listed here. Before making a decision, you may want to explore tools such as FileMaker (a wholly-owned subsidiary of Apple), which is designed for use by non-programmers. Originally a database application, FileMaker now has become a key tool for people who may never write a line of code in their life but are comfortable (and happy!) spending their time analyzing data and the processes that use it. Give FileMaker a look — particularly if your app idea is data-related.
In terms of cost and difficulty, FileMaker is likely to be your best choice; Titanium Appcelerator, PhoneGap, and HTML5 the second-best; and native app development with Swift or Objective-C (or both) the third. In terms of flexibility, however, this order would be reversed — the native apps are the most flexible, and tools like FileMaker are the least.
If your goal is to “get an app deployed by next Tuesday,” FileMaker may be your best bet (if it can be done at all). On the other hand, if your goal is to build something that will last or — perhaps more importantly — something that will develop your skills and expertise in this rapidly-growing mobile world, native apps with iOS and OS X are usually the way to go.
The tools you need to develop with Swift for iOS or OS X are simple:
A Mac:
Any current Mac has enough processor power and memory to build apps. As of this writing, you must be running Mavericks (OS X 10.9) or Yosemite (OS X 10.10).
Xcode:
Xcode is the integrated development environment (IDE) for building OS X and iOS apps. You can download it for free from the Mac App Store.
These are the essentials: They’re really all you need. However, a few additional tools can be very helpful — even necessary for some developers — but if you don’t have them, don’t worry about it. There are some workarounds and compromises if you’re missing these tools. They include:
An iOS device (if you’re developing for the iOS platform):
It’s possible to develop an iOS app with no hands-on experience, but the results will show, particularly when you get reviews in the App Store along the lines of, “Hasn’t the developer ever tried to use an iPhone?” Writing an app based on an understanding of iOS devices gained from articles and advertising is very difficult. It’s much easier if you have access to the real thing. The one exception to this is when you’re working on only a component of a larger app, one that doesn’t involve the user interface.
Internet access:
If you only have intermittent Internet access, you can still develop, but with limitations. Certain tasks, such as getting your app into the App Store, require Internet access.
Plenty of disk space and a robust backup mechanism, such as Time Machine:
“Plenty of disk space” can mean a large internal disk, one or more external disks connected to your Mac, or cloud-based storage. The backup mechanism is important because you need to be confident that all of your project’s files are properly backed up and can be restored, if necessary.
The Apple developer discussion boards (Apple Developer Forums, located at https://devforums.apple.com) provide a valuable resource, as I describe in the following section. Every few months, a plea for help shows up on those boards that goes something like this: “How do I get my app into the App Store? I’ve written it and now I have to get it into the App Store.” (Such questions pop up in other places on the Internet as well.) Native apps need to be written in Swift or Objective-C, and they must abide by the rules of the App Store and the Mac App Store. Make certain you understand this before you start work. Writing an app in Java, HTML5, JavaScript, Objective-C without the Cocoa or Cocoa Touch framework, or even COBOL counts only as a personal experiment with a user interface; your app can’t be moved into the App Store. You may be able to distribute it as an app-like website, but not as a native app. Along those lines, the various commercial app development frameworks and services may or may not be useful to you.
This section provides a quick overview of setting up your Mac for development in general and for Swift in particular. The basic steps are included here, and, as you’ll see, each one can open a variety of doors to additional steps and information.
The basic developer tools are free, and you can start work immediately, but Apple requires that you register as a developer at developer.apple.com before you can access many of the tools and features that you’ll need, particularly for testing. More and more of the developer website is available without logging in, but some of the key features require registration.
Not only do you need to register, but in some areas of developer.apple.com, you need to sign a non-disclosure agreement. You will be invited to join a developer program, which may entail an annual fee (see the upcoming section, “Choosing your program,” for more on this), but if you’re on a limited budget or just exploring, you can get quite a long way by saying “No, Thanks” to the offers. Rejecting offers like these and surveying the site is a good way to get your feet wet and get a good general understanding of the environment — although it does not let you submit your apps to the App Store.
The rules and policies of Apple’s developer programs change from time to time and from country to country. Look at developer.apple.com for the latest definitive information. Be particularly careful of web postings you find that may be from the past. Always check the posting date from any articles you rely on — and that includes articles from Apple on developer.apple.com. You can usually find this date at the bottom of an article.
For basic registration, you need to identify yourself to Apple. The standard way of doing this is to provide an Apple ID. Your Apple ID is not confidential, but your password is. Go to appleid.apple.com to register or to manage your Apple ID (including changing your password, if you want).
You may have more than one Apple ID (and you may need to have more than one, in some cases). Some developers have separate Apple IDs for personal use in addition to ones used for development. You may have a different Apple ID for developing apps than you have for developing iBooks — in fact, at the moment, this is a requirement.
For more on this, see the section, “Planning Your Environment,” later in this chapter.
Apple offers a number of different developer programs in which you can enroll. The simplest one is an individual program, which, at the moment, costs $99 a year, with separate programs for iOS and OS X. Thus, if you register for both, you’ll pay $198 a year.
You can also register as a business. This registration allows you to build teams of individual developers and share code among yourselves as you develop apps.
There are also programs for educational institutions. Make certain that you have an Apple ID that you will use for your development, and then choose your program. If you are working for a business or are enrolled in a school, check to see if you are eligible to join a program there: It may save you some money.
Your development environment is centered around a Mac with Xcode installed on it, but you can use several Macs for development. Each one should have Xcode on it (see further topics in this section for a discussion of multiple versions of Xcode). Because Xcode is free, it’s easy to install it on a number of Macs. In fact, if you have access to a shared computer lab (perhaps at school), Xcode may be a component that is part of the lab.
There are no special settings to use Xcode with Swift, except to choose Swift (rather than Objective-C) from the pop-up menu when creating a new project or file. You also need to download the latest Swift documentation and SDK, but this is part of the standard installation process. If you are working with an old version of Xcode, you may be better off downloading and installing a new version of Xcode from scratch and proceeding from there. Your older Xcode projects should be able to be opened (and automatically converted if necessary) by the new Xcode.
Source control is built into Xcode with both Git and Subversion. Because of its architecture, Git is more closely integrated into Xcode than Subversion. If you use one of these tools, you can easily store your source code in a repository. If you make a practice of committing changes to your source code repository on a regular basis (at the end of each work session perhaps, or when a significant milestone has been achieved), you’ll know that you can download the project on demand.
Using source control means that no matter which Mac you find yourself using, as long as you have a network (or Internet) connection, you can check out the latest copy of the project (or a branch thereof), make your changes, and then check your files back in. And the next time you want to work on it, just check out the project on another computer and keep going.
Whether you're working on a single-developer app or a multiple-developer project of a large-scale system (think of the iOS and OS X operating systems), managing your source code is essential. This management, known as source code control, is sometimes referred to as source control or revision control.
For individual developers, source code control begins by having good, routine backups, often by using Time Machine. The next phase usually is an ad hoc and idiosyncratic process: creating a folder for each day’s or week’s work and then copying it over to a new folder on the following day or week. Together with Time Machine, which helps ensure the preservation of the various physical files, these folders provide you with a periodic backup of the entire project. (This is necessary because there are rare occasions when Time Machine’s backups won’t let you easily restore all of the files in a project to a specific time. This happens particularly when you use Xcode's default file locations).
Source control products such as Git and Subversion (both free, open-source projects) let you manage changes to your files. Whereas Time Machine and a file/folder structure focus on the files, source control focuses on the evolution of your app. You can define branches of code, and branches of branches, and you can identify these branches by name — “Implement Multi-User Preferences” for example — rather than just by date and time. The source control product keeps track of the date and time for you.
Both Git and Subversion are designed to allow multiple people to update a project (called a repository, or repo in these contexts). By keeping track of multiple branches and multiple people, you have an orderly process that lets you follow the development of a project.
When you start to work on a project, you check it out from the repository (with a check-out message you provide). When you're done, you either drop it (in the case of an experiment that fails), or commit it back to the project (with an explanatory message).
In addition to following the development, you can manage the project’s development as you merge branches into one another, drop others, and generally prune your development tree.“
A key part of source control is the ability for multiple users (or even a single user) to check code in and out either as part of an existing branch or a new one. If you think that your little experimental project is too small for source control, you may want to think again. Because you may eventually work on (or even manage) larger projects, you should get used to the source control process. Further, even if you're just one person, source control is a good way to manage your development over time. When a bug appears and you have to return to something you wrote a year ago, source control — particularly with the check-out messages you provide — can be a critical part of your troubleshooting and problem-solving process.
Your environment may include a shared source code repository that you can use, or you can create your own environment on a remote server such as www.github.com, which uses Git to manage the files you add to Github. The cost is not great, and it allows you (and perhaps your colleagues) to work together on a project on various Macs. When you’re confident that your source control is working properly (and, more important, when you understand how to use it properly), you can forget about keeping files and folders labeled “Thursday version before restructure” and “Friday version after restructure.” If you haven’t used source control, now is a good time to get familiar with it.
If you’re using Git or Subversion (or another source control tool), you can cross “Organizing files” off your to-do list right now. Xcode manages files within the project folder for you, and the source control software manages changes to those files using its repository. (Preferably this repository won’t be on your own disk.)
The only thing you have to do is to trust Xcode and your source control software. If all of your files are within a single project folder (which is the Xcode default), just leave them there. Don’t move them around or rename them.
During your development process, it is very likely that there will be changes to your environment. In addition to the changes you make to your project, there are likely to be other changes you should prepare for. The most important are the new releases of Xcode, OS X, and iOS.
Review the releases of these products over the last year on https://developer.apple.com/downloads, and you may see a pattern. (Note that this address may change. In addition, access to this site may be available only to registered developers.) At this writing, the release cycle is as follows:
Early June:
Apple’s Worldwide Developer Conference (WWDC) provides updates of upcoming releases. It typically has previews and demonstrations of new operating systems and their features. It doesn’t normally have product announcements. Developer previews of iOS and OS X may be distributed to attendees as well as to registered developers.
Summer:
Updates to developer previews are distributed to developers and sometimes to users who want to beta test software.
Early fall:
New devices (often iPhones) are announced and the new iOS is made final.
Late fall:
Other iOS devices are announced along with new Macs. A new OS X is made final and released.
Winter and spring:
Quiet on the developer software front (but pretty busy behind the scenes at Apple). This is the time to follow the Apple developer discussion boards closely and to file bug reports and requests (for registered developers only at this time).
As new releases of the OS X operating system and Xcode (including new SDKs for iOS and OS X) ship to developers over the summer and fall, you need to decide if you will install them and which version(s) you will support. You don’t have to make this decision now, but you should think about how you will handle these updates.
If you can, you may want to have one complete development environment for current production (including your own personal software, emails, and documents) and a separate one for testing and development.
Every developer has a different environment, although it can change from time to time (depending on what they’re working on and where they’re working). I've sometimes been asked what I recommend, and my answer is that I can only tell people what I use. So here's that answer. Remember, this is only the environment that works for me.
My primary device is a Mac Pro with a Thunderbolt screen. I like the speed and expandability of the Mac Pro and the size of the display. This is not the cheapest alternative, but because I spend almost all of my working time every day at the computer, it's worth it to me. The Mac Pro is backed up via Time Machine to an external disk.
If I wanted a less expensive primary device, I would use an iMac. Many developers use an iMac, and you don't even need the top-of-the-line model.
In addition to my Mac Pro, I have a 2 TB disk configured as a RAID disk (that is, two 1 TB disks that mirror one another). It is connected to a UPS so that a power failure is unlikely to damage the files (although that has happened). This disk is connected to an Airport base station so I can access the files from my desktop as well as remotely over the Internet. I use this disk for backup copies of everything I'm working on.
I have a stack of MacBook Pro computers on my desk. At the moment, the stack consists of four computers dating back several years. The most recent is on top, and I move files to it as needed when I head out for a meeting, conference, or even time off(!). The other Mac Book Pro models are kept in chronological order. I don’t use them for storing archival versions of files — that’s what the shared disk is for. I use them for old versions of the operating system. On each one, I have several user accounts for different types of projects.
I could achieve many of the same results by partitioning disks, but my preference is not to partition disks because every once in a while I wind up with a project that really needs an enormous amount of disk space.
That's how I work. If any of those ideas are useful to you, feel free to make them your own.
It’s very difficult to discuss any computer language in the abstract, so in this book, I provide an example application that you can use to follow along with the syntax discussions. (I show this earlier in this chapter — in Figures 1-1 through 1-5.) The various files for this application are discussed over the course of many chapters. You can download these files from this book’s companion website, as described in the Introduction. (Not every chapter has code from the example. This is because my priority here is to describe Swift and, strictly speaking, exploring the use of the Cocoa and Cocoa Touch frameworks is beyond this scope. However, by experimenting with Swift features that you may one day use in your own apps, you can better understand how the language works with the frameworks.
The example application uses a built-in Xcode template called Master-Detail Application for iOS. This template has some additions that allow you to access social media and the location tools with the features built into iOS.
This section has two components:
Installing Xcode and setting your preferences.
Creating your own project to use.
As noted, you can download sample code for many of the chapters in this book. You must create the two components listed here before your downloaded code can work, so you’ll see the steps involved here.
Begin by registering as a developer and downloading Xcode from the Mac App Store, as described earlier in this chapter. If you’ve already done these things and you’re eager to get started, feel free to skip ahead — to the “Creating your project” section, later in this chapter — but be aware that setting up your preferences as described in this section can be useful. It takes only a few minutes to familiarize yourself with the Xcode preferences. Whether or not you use the default settings, just knowing which settings are available can save you hours and hours of time. If you’re trying to figure out how to do something — such as how to make your version of the example look like the version in this book — these settings can be a help.
It’s easy to find helpful tips about adjusting your settings and preferences on the web, but be aware that these may be out of date. Over time, Apple has refined Xcode, so some of the features in the version you downloaded may be new or may be accessible in a new way.
Here follows a step-by-step tour of the major preferences in Xcode. Work through each step to familiarize yourself with the various settings, or come back later on to look at specific settings. In each of the step lists that follow, I’ve assumed that you’ve set up your environment as described earlier in this chapter.
It’s not essential to use a developer account at the beginning, but, considering the fact that registration can be free, it’s a good idea to have one so that you can use it when you need it. Here are the steps to follow to get a developer account:
Launch Xcode.
Choose Xcode⇒Preferences.
Select the Accounts tab.
Using the + at the bottom left of the window, add a new account for an Apple ID that you’ve registered on
developer.apple.com
.
This can be a free registration or one of the paid programs.
Enter the appropriate Apple ID and password along with a description of the account.
For the description, use the Apple ID or a few words that identify the account, such as “School” or “Freelance gig for GUKL.”
Verify that the information for the account is shown in the main section of the lower-right, as shown in
Figure 1-6
.
Any source code repositories you’ve set up will also be shown in this window. You can return to this window to add repositories or additional developer accounts.
Figure 1-6: Setting your developer account.