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:
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.
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.
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:
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.
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.
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.
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
In this part . . .
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.
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:
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:
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:
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.
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.
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.
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.
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:
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.