Setting Up an Xcode Swift Project - Getting Started with Swift - Swift For Dummies (2015)

Swift For Dummies (2015)

Part I. Getting Started with Swift

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. Setting Up an Xcode Swift Project

In This Chapter

arrow Introducing Swift

arrow Setting up your computer for Swift

arrow Defining your development preferences

arrow 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.

icon tip 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.

Looking Ahead to the End

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.’”

Working with Swift

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.

Getting the Developer Tools

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.

icon tip The Apple developer discussion boards (Apple Developer Forums, located at 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.

Setting Up Your Mac

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.

Registering as a developer

The basic developer tools are free, and you can start work immediately, but Apple requires that you register as a developer at 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, 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.

icon tip The rules and policies of Apple’s developer programs change from time to time and from country to country. Look at 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 You can usually find this date at the bottom of an article.

Preparing your credentials

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 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.

icon tip For more on this, see the section, “Planning Your Environment,” later in this chapter.

Choosing your program

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.

Planning Your Environment

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.

Using source control

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.

Source code control

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.

Using GitHub

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, 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.

Organizing files

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.

Preparing for environmental changes

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, 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.

My development environment

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.

Getting Started with Swift

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.

Installing Xcode and setting preferences

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.

icon tip 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.

Obtaining your developer account

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:

1. Launch Xcode.

2. Choose Xcode⇒Preferences.

3. Select the Accounts tab.

4. Using the + at the bottom left of the window, add a new account for an Apple ID that you’ve registered on

This can be a free registration or one of the paid programs.

5. 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.”

6. 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.

Setting preferences with Fonts & Colors and Text Editing

Some developers may prefer to write code in dark text on a white background, and some prefer light text on a black background. This has nothing to do with anything except your preferences (and the lighting in your room). Xcode allows you to control these settings to make your code look the way you want. It has a variety of defaults, but you can create new settings as well as modify existing ones.

These preferences are applied to each file you work on, inasmuch as that’s possible. Some preferences (such as spacing and indentation) rely on spaces within the file, and changing the preference settings affects new code you type in, so changing them in the middle of editing a file has the potential to make the spacing a bit erratic. ( That's one reason why developers tend to set them and leave them alone after that.) Other preferences (such as syntax color highlighting) reflect the preferences only and do change in the files when you change the preference.

In all cases, your preferences or the code-formatting settings you make won’t affect the syntax. Changing, say, the font of the code can neither fix a syntax error or cause one. Even if this appears to be happening, something else is at work.

To change text styles, follow these steps:

1. Choose the Fonts & Colors tab. (See Figure 1-7.)

2. In the right pane, each type of syntax element appears in the color assigned to it in the source editor and in the console. Use the tabs at the top of this pane to switch.

3. In the left pane, choose from a variety of styles.

Note that the colors and also the sizes vary.

4. Adjust the color for any selected style by clicking the Background, Selection, Cursor, or Invisibles color wells at the bottom.

Clicking these brings up a color picker you can use to modify that color.

5. To select a new font and size, click the Font field.

This opens the Font window.

6. Use + at the bottom left to add a new style.

You can provide a title for the new style, as well as set colors and fonts.


Figure 1-7: Setting fonts and colors.

icon tip To experiment with these settings, begin by creating a new style (as shown in step 6) before you modify the existing styles.

Use the Text Editing tab to set editing and indentation preferences. The editing preferences are shown in Figure 1-8. Most of the checkboxes are self-explanatory, but a few might benefit from some elaboration:

· Code Completion: This setting activates Xcode’s autocomplete feature. As you type, Xcode will offer to complete words and will automatically track parentheses and braces (or “brackets” if you prefer that word).

· Automatically Trim Trailing Whitespace: This setting removes spaces at the end of a line (unless they are inside quotation marks). This can slightly reduce the size of your source code file, but it also can make it easier to copy your code and paste it elsewhere.

· Convert Existing Files on Save: This option applies your settings to old files when you save the files.


Figure 1-8: Setting general editing preferences.

Xcode automatically manages your code’s indentation using the settings shown in Figure 1-9. The settings for indentation allow you to choose between using tabs and spaces for the indentations. If you commonly copy your code and paste it into other editors (perhaps into a word processor), indenting with spaces may make that operation easier.


Figure 1-9: Setting indentation preferences.

Perhaps the most important point to make about the indentation settings is that they’re not merely cosmetic. With Xcode managing the indentations, you have immediate feedback of certain syntax errors. If your code isn’t aligned or indented properly, chances are you’ve missed (or added) an extra parenthesis or bracket or end or begin (and so on).

Setting behaviors

Figure 1-10 shows you some of the settings in the Behaviors tab. For each of the events at the left, you can choose the various actions shown at the right. As an example, among these settings is the one that, by default, makes the Debug area appear below the Editing area when you run an app in Xcode. (This is true whether you run it with a tethered device such as your iPhone or on iOS Simulator which is built into Xcode and lets you test your code without using a device.)


Figure 1-10: Setting behaviors for Xcode events.

Judging from comments on blogs and websites, I’d say that the settings in this tab are among those that developers most want to change (or stop). If you wonder why Xcode does certain things (or doesn’t do others), take a look at the settings on the Behaviors tab.

Setting navigation preferences

The Nagivation tab (see Figure 1-11) lets you set preferences for the way windows behave and appear. If you find yourself constantly changing the appearance of your Xcode workspace window (particularly when using the Assistant), you can make those changes once and for all in navigation preferences.


Figure 1-11: Setting navigation preferences.

Downloading new components

The Downloads tab, shown in Figure 1-12, is where you download more components, SDKs, and document libraries for Xcode. When you install Xcode, it comes with the current documentation and components (and, sometimes — if you’ve downloaded it from a preview section of the Developer site — with beta versions of the next releases). If you are supporting previous SDKs, you may need to download them and their related documentation manually: This is where you do that. (Many developers follow Apple's lead and design apps to support both the current operating system and one prior. Typically the current system's SDKs are downloaded with Xcode, and the first prior may also be there. You'll need to manually download others if you want to support them.)


Figure 1-12: Downloading new components and documentation to Xcode.

Downloading new components and documentation requires an Internet connection. After the materials have been downloaded, you can disconnect from the Internet for further work.

Setting file locations

The last item in this very quick overview of Xcode settings is the Locations tab, shown in Figure 1-13.


Figure 1-13: Working with file locations.

The Locations tab on Preferences lets you set and change the locations for the various files that Xcode uses in building your projects. You can change these locations, if you know what you’re doing, but be careful: The most frequent case in which you need to know where those files are is if you want to go beyond the Clean command for your project. Clean (Command-Shift-Key or Product⇒Clean) cleans most of the build product results from your project. Removing or moving files in the directories shown in Figure 1-13 can cause Xcode to lose track of them and, before you know it, you can't build your app any more. So be careful.

A more thorough cleaning comes from Window⇒Organizer and the Projects tab where you can delete the derived data from wherever it happens to be (that is, from the location shown in the Locations tab). These two commands (Clean and Delete Derived Data) are safer than just deleting the files from disk. Doing that can have nasty side effects as noted in this section.

Creating your project

The project used for examples in this book, Locatapp, is based on the iOS Master-Detail Application template built into Xcode. In this section I give you an overview of the steps you must follow to create your own version of that template to experiment with.

You can download a complete project folder from this book’s companion website, as described in the Introduction. There you’ll find separate folders for the various chapters in which the example is used.

The following steps show you how to create your own project. You can follow these same basic steps to create any new project in Xcode:

1. Click File⇒New⇒Project or Command-Shift-N.

Click Next.

2. From the sheet that appears, choose Master-Detail Application in the iOS/Applcation section.

Click Next.

3. In the Options window (see Figure 1-14), enter the product name (Locatapp if you’re duplicating the example in this book).

4. Add your organization name.

You can use spaces and special characters in the name.

5. Enter an organization identifier.

This is typically a reverse domain name as in or org.unicef. The style is used in Java and is based on the idea that if your domain name is unique on the Internet (and it is), the reverse domain name will also be unique, and yet it can’t easily be confused with an actual Internet address.

Note that the bundle identifier will automatically be created from the organization identifier and the product name. Spaces and special characters will automatically be replaced by a hyphen.

6. Set the language to Swift.

The alternative is Objective-C. If you want to create an Objective-C project, you’re reading the wrong book! It is important to note that projects in either Objective-C or Swift can contain files in the other language — so, strictly speaking, there’s no such thing as a Swift project or an Objective-C project.

7. Set Devices to Universal.

You could also choose to target only an iPhone or iPad.

8. Check the checkbox for Core Data.

Core Data is the technology to create and use a persistent store. It is independent of the specific data store technology, but in iOS apps, the built-in SQLite library is frequently used (it’s the default). On OS X, SQLite can be used, but XML is also a supported choice.

9. Click Next.

10. Select a location for your new project, as shown in Figure 1-15.

Note that you can use the button in the lower-left to create a new folder for the project; however, any new project is automatically placed in its own new folder, so the New Folder button is generally superfluous.

11. (Optional) Implement source control by checking the Source Control checkbox.

If you use source control, choose a repository on your Mac or any other known repository. (Known repositories are defined in the Xcode Account preferences, as shown previously in Figure 1-6.)

12. Open the Add To pop-up menu to choose a project or workspace to add this new project to.

If you’re a beginner with Xcode (or even a moderately advanced user), leave the default setting — don’t add to any project or workspace.

13. Click Create.

That’s it! You’ve created your first project, and you’re ready to explore it.


Figure 1-14: Setting options for the project.


Figure 1-15: Choosing a location for the project.

This is a high-level overview of working with Xcode and creating a project so that we can get into the details of using Swift as quickly as possible.

icon tip It’s always a good idea to make a duplicate of your project folder as a backup. An easy and safe way to do this is to locate the folder in the Finder (in the location you chose in Figure 1-15). With the folder selected, use File⇒Compress or Control-Compress to create a Zip archive. That way you’ll have a duplicate, but because it’s hidden inside a Zip archive, you won’t be able to accidentally modify it.

Exploring Your Project

This section helps you walk through the project you’ve just created. Here you make a single change — you replace a view from the template with a map view that you’ll later use in your code.

Touring your new project

To look over the details of your new project, follow these steps:

1. Display the project navigator and the editing area as you see in Figure 1-16.

2. Select the project — it’s at the top of the project navigator.

You may need to open it with the disclosure triangle to the left of the project.

At the left of the editing area you’ll see each project and its targets. You can display and hide this section with the button just above it.

3. In the General tab, make sure the bundle identifier is correct.

4. If you’ll be using a development team, set it in the Team drop-down menu, as shown in Figure 1-17.

You can add this later or change it as you work. You don’t need it for now, but it you have one set up in the Account tab of Preferences, you might as well use it.

5. Check the device orientations and update them if you want.

If you want to change them later on, make certain to clean the project and delete intermediate files as described in the section, “Setting file locations,” earlier in this chapter.

6. Click the Capabilities tab to see the Cocoa and Cocoa Touch capabilities you can use, as shown in Figure 1-18.

This list grows over time as Apple adds new devices and features. Many of these capabilities rely on using a team with the appropriate permissions and provisioning profiles. Don’t worry: If you need additional capabilities, they and the provisioning information will be provided in new releases of Xcode (possibly in beta versions downloadable from

7. Open at the Info tab to see your target’s property list. (See Figure 1-19.)

This is where you can change the bundle name that the user sees or the bundle identifier. The bundle identifier may need to be shared if you are using iCloud. Here’s where you change it if necessary. (The bundle is the internal identifier for your app; it's separate from the app's name. There's more about bundles on Use the search tool there to find a number of references and documents.)

8. Check the Build Phases tab, as shown in Figure 1-20.

Build phases are normally set for you as you add or remove files to or from the project. If at some point you have mysterious errors, you can check the Build Phases tab to ensure that all your source files are being included and that no extraneous ones appear in the list. You can use the + and – buttons below the lists to adjust them.

9. Explore your Swift files.

You can look over these at this point, but don’t touch. Look at the text fonts and coloring. If you don’t like the way your code looks, adjust those preferences until the code looks meaningfully colored and indented. You may also want to resize your window to make lines wrap better. Remember that you can show and hide the navigator and utilities areas at the left and right of the window. Experiment!

10. Build and run the project.

Use the arrow at the top left to build and run the project. You can choose to run it in iOS Simulator or in a tethered device. For now, however, try using one of iOS Simulator options (it doesn’t matter which one).

11. Make certain you see the launch image, as shown in Figure 1-21.

If you used a different name for your app, you’ll see it on the launch screen instead of Locatapp.


Figure 1-16: Checking out the project settings.


Figure 1-17: Setting the team.


Figure 1-18: Reviewing capabilities.


Figure 1-19: Reviewing the target’s property list.


Figure 1-20: Reviewing build phases.


Figure 1-21: Viewing the launch screen.

Adding a map to the project’s interface

A lot of your work in app development has nothing to do with Swift, Objective-C, or any other language. Much of it has to do with the user interface that you build and, with many of the templates built into Xcode, with modifying the basic template.

The example app, Locatapp, is a case in point. The Master-Detail Application template on which it’s based lets you add data elements to a list (in the master detail list). Each element (called an Event) consists of a timestamp. In addition to creating new data elements, you can also delete existing ones. You can select any of the data elements and see the details in a detail view.

For Locatapp, you must modify the template so that instead of creating data elements with timestamps in them, you create data elements with a location (latitude and longitude) in them. By doing this, instead of selecting an Event from the master detail list and seeing its details in a detail view, you can select a Location from the master detail list and show its location on the map.

To prepare for this, you must change the detail view controller so that instead of text it displays a map on which you can place pins marking locations. The following steps show you how to replace the detail view with a map view:

1. Open LaunchScreen.xib, the user interface file for the launch image (the editor is called Interface Builder).

As you see in Figure 1-22, in addition to the project navigator at the left, you also have a document outline at the left of the Interface Builder editor. You show and hide the document outline with the small icon at the bottom left of the canvas view (with the word Locatapp in large letters).

2. With the document outline open, click on the copyright notice in the canvas. Note that the copyright notice is highlighted in the document outline automatically.

icon tip You may have to open some disclosure triangles to do this.

In Figure 1-22, the copyright notice at the bottom of the canvas is highlighted as is its representation in the document outline.

The L in the document outline indicates that this is a label object. The handles around the copyright notice in the canvas indicate that it can be moved and resized there.

Note that at any given moment, you may see some objects only on the canvas (the editing area) or only in the document outline.

3. Repeat the process by selecting an element in the document outline and watching it become highlighted on the canvas.

Try this with the label (marked with an L) for the Locatapp title.

4. Select Main.storyboard in the project navigator.

This is the primary user interface element.

5. Open disclosure triangles as necessary to reveal the Detail view controller (a yellow circle) and a view labeled View within it, as shown in Figure 1-23.

Within View, you’ll see a label with the text “Detail view content goes here” and a Constraints folder.

6. Open the library at the bottom of the utilities area, and drag a MapKit View into the document outline.

Place it on top of View. Make certain that it replaces View and is not placed within the View folder. The layout guides may disappear. The document outline should look like the one in Figure 1-24.

You can display the Identity inspector in the utilities area, as in Figure 1-24, but you don’t need to make any other changes at this point.

7. On the project’s General tab, add the MapKit framework to Linked Frameworks and Libraries, as shown in Figure 1-25.

If it’s already there, don't add it a second time.


Figure 1-22: The Interface Builder editor.


Figure 1-23: The storyboard.


Figure 1-24: Using the Identity inspector for the map view.


Figure 1-25: Adding the MapKit framework.

Your app should run now. It won’t do much except create new Event objects with timestamps, and it will display a blank map that’s ready for you to work with it.

You now have a bare-bones Swift app built on the Master-Detail Application template. As you explore the project, you’ll see that not only do you have an interface, but you also are running with a Core Data persistent store that’s implemented with the built-in SQLite library.

Not bad for a few keystrokes! Now it’s time to move on to more Swift tools before delving into the language itself.