Using the Xcode Editing Tools - Getting Started with Swift - Swift For Dummies (2015)

Swift For Dummies (2015)

Part I. Getting Started with Swift

Chapter 3. Using the Xcode Editing Tools

In This Chapter

arrow Working with Xcode editing tools

arrow Using code completion features

arrow Correcting code with Fix-It

arrow Using code snippets

In Chapter 1, I show you how to get started with an Xcode Swift project. As you can see in that chapter, a great deal of your Swift Xcode development involves the graphical user interface of Xcode. A lot of the work — particularly at the beginning of a project — is graphical or involves checkboxes.

In Chapter 2, I show you how to write and test code — particularly small snippets of code — in a playground. This helps you learn Swift syntax and allows you to test out code fragments before you type them (or copy-and-paste them) into your project files.

Now, in this chapter, I introduce Xcode’s editing tools. Here, you’ll write code in the way you may have written it in your beginning programming class in school (that is, typing in code rather than drawing the interface and using Xcode checkboxes and other graphical elements to construct your app visually). The focus in this chapter is on the Xcode tools that assist you with writing code. Much of what Xcode does for you in regard to typing and editing text is made possible by the fact that it observes every keystroke and keeps track of the syntax of the terms you type (or copy-and-paste).

With the tools and techniques you find in these first three chapters, you can create your first Swift app — the Locatapp example app used throughout this book. (In case you haven't seen it yet, you can look at Figures 1-1 through 1-5 in Chapter 1 to see where you're headed.)

Getting Started with Editing Tools

The editing tools and techniques described in this chapter help you code with Swift and build your apps. Many of these editing tools apply both to Xcode itself as well as to the playgrounds that you create with Xcode. The examples here focus on the editing process; you’ll use these tools as you write and edit the code in the rest of the chapters in this book.

In my discussions of these various editing tools, I include examples of Swift syntax, some of which are deliberately incorrect so that you can use the appropriate editing-correction features. The syntax itself is discussed in the later chapters of this book.

Completing Code with Code Completion

As noted previously, Xcode “watches” your keystrokes, which enables it to suggest code as you type. This feature is called code completion, and it’s a great time-saver. Here are some examples of its use, along with some things to watch out for — just as you can sometimes make mistakes, so can Xcode’s code completion!

Code completion is the name of the technology. In the user interface of Xcode, however, it’s referred to as Fix-It.

As you may recall from Chapter 1, to create a new project, first launch Xcode and choose File⇒New⇒Project, select a template, and choose a name and location for your new project.

Similarly, as I show in Chapter 2, you can create a new playground by: launching Xcode, choosing File⇒New⇒Playground, selecting Swift as your language, and entering a name and location for the playground.

Using basic code completion

The following steps take you through your first demonstration of code completion. This demonstration uses a playground:

1. Create a playground, as shown in Figure 3-1.

You can base it on iOS or OS X. The figures in this chapter happen to show iOS.

You can delete the initial text if you want. Playgrounds begin with a comment, an import statement, and a string variable set to “Hello, playground.” Leave those or not, as you wish.

2. Begin typing in the code to create a variable — var myVar: String. Slowly type var myVar: S.

Go slowly to allow code completion to do its work (not because code completion needs a long time to work, but because going slowly will give you a sense of how long the process takes on your Mac with your specific configuration). Shortly after you type the S, you’ll see that the rest of the word String is filled in using gray text. Depending on your preferences, the S may be blue (the default value) or some other color, whereas the suggested completion (String) is gray.

3. From here, you can do any of three things:

· Accept the completion: If the suggested completion (String) is what you want, press Return and the suggestion is accepted. The gray of String changes to the same color as the initial S.

· Hesitate: On the other hand, if you hesitate before accepting the suggestion, additional completion suggestions will appear in a list on top of the playground, as shown in Figure 3-2. Note that the list of additional completions is scrollable: A lot more choices are available than the ones shown in Figure 3-2.

· Continue typing: If you continue to type Strin, the list of completion suggestions gets shorter, as shown in Figure 3-3. Click a suggestion from the list, and it will replace the text in the playground. At any time, you can press Return to accept the suggested completion.

image

Figure 3-1: Creating a playground.

image

Figure 3-2: Hesitating produces additional code completion suggestions.

image

Figure 3-3: As you type, the list of suggested completions gets shorter.

Using code completion in a project

Code completion doesn’t just look at what you're typing; it also looks at the context of what you're typing. The following steps show you how code completion interprets according to context:

1. Begin by creating a new project based on the iOS Master-Detail Application template.

If you need a refresher, refer back to “Creating your project” in Chapter 1.

2. Open the project navigator at the left of the workspace window (if it’s not already open) either by using View⇒Show Project Navigator, appleinline-1, or the button at the right of the toolbar to show or hide the project navigator.

3. If necessary, open the project folder in the project navigator.

4. If necessary, open the project group (it has a folder icon, but it’s a group).

5. Scroll to the top of the AppDelegate.swift file, as shown in Figure 3-4.

6. Just below the var window: UIWindow? line, begin typing in the code to create a variable — var myVar: String — much as you did in the preceding section.

A list of code completion suggestions appears, as shown in Figure 3-5. Notice that this list isn’t the same as the list you generated in the previous section. New choices — UnsafeMutablePointer < StringPtr > and UnsafeMutablePointer < UInt8 > — now appear in the list. These completions in the Xcode environment are possible because of the syntax that surrounds them.

image

Figure 3-4: Using AppDelegate.swift.

image

Figure 3-5: Completion suggestions depend on context.

Working with code completion

Code completion changes and evolves over time. Even if you've used it before, you may find it has features that weren’t available when you first learned it. To get the most out of it, try some of these tips:

· Pay attention to the color of the text as you type: Versions of this book that are in color (mostly eBook editions) use the Presentation style in Xcode Preferences (the Font & Colors pane). Settle on a style you like and stick with it so that you can recognize when the coloring changes. If the coloring looks wrong, Xcode is probably not recognizing your syntax — the most common reason for this is that you’ve entered a typo. For example, if you type myVar: S instead of var myVar:S, the S will remain uncolored (black by default).

· To regenerate the code completion suggestions, use Delete to backspace to a point in your code before the first letter that seems colored correctly: For example, if you want to regenerate the suggestions for S, back up to the space before it and retype S.

· Consider using code completion even if you’re a fast typist: If you type quickly, you may not think you need code completion — but don’t be so sure. Not only does it save you keystrokes, it also completes the code accurately, and fast typists can always make mistakes.

· Remember that code completion is accurate — but it’s not infallible: Code completion doesn't make mistakes, and yet sometimes its completions are wrong. Take the preceding example: Omitting var causes code completion to misbehave with String. If you were to continue on, the compiler would issue an error on String — even though the problem is the absence of var, not String. So although code completion is context-sensitive and doesn’t make typos, simple errors can still throw it off-track.

· Always look at the suggested completion before pressing Return: Most of the time it’s either correct or it’s an obvious misinterpretation of your intentions. But sometimes, you do have to intervene to correct a misinterpretation, and in those cases, you must type the code yourself.

Using Fix-It to Correct Code

Fix-It is related to code completion in that it relies on the background processing of the text that you type, but it goes beyond just correcting typos. (As noted previously, Fix-It is the user interface name for code completion.)

Figure 3-6 uses the Master-Detail Application template to demonstrate this. (As mentioned earlier, use a copy of the project for these exercises, not the one you're planning to use for the rest of this book’s examples.)

image

Figure 3-6: Fix-It can catch contextual errors.

Earlier in this chapter I showed you how code completion can help you complete the code when you type var myVar: S. However, after you've typed (and completed) var myVar: String, you still have a syntax error.

An error message appears on the class declaration. The text is shown at the right (“Class ‘AppDelegate’ has no initializers”), and the red circle in the gutter indicates an error. (See Figure 3-6.)

This red circle — really a red doughnut — won’t always accompany your error. Some error messages display a small red stop sign in the gutter instead. The red doughnut indicates that Fix-It is available. Click the doughnut to add a suggested Fix-It, as shown in Figure 3-6. Press Return and Xcode implements the Fix-It.

In this case, the error is the missing initializer for the class. That's all well and good, but if you're a beginning Swift developer, what do you do about it?

The Fix-It provides the solution. Swift requires that every variable and constant have an initial value. Unlike some other languages (including Objective-C), you cannot have a declared constant or variable that has no value. It has to have some value. Thus, to adhere to the Swift rules, you can get rid of the error message about the lack of an initializer by setting myVar to a blank string. It’s only a blank string, true, but it’s something. By using it, you don't have an uninitialized variable, and your error goes away.

Figure 3-7 shows the Fix-It and its solution.

image

Figure 3-7: Fix-it corrections can go beyond typos.

Fix-It is very powerful. Consider, for example, that instead of var myVar: String you had entered the following line of code:

var myVar: Double

This new code gives you the same Fix-It message. However, the Fix-It solution would be different:

var myVar: Double = 0.0

Fix-It can not only recognize that myVar is uninitialized, but it can also provide an initialization that is the correct type. It gives you a solution that’s syntactically (and contextually) correct.

Note, however, that even a syntactically and contextually correct solution may not be right. The best initialization value for your needs might actually be “No Data” (for the string) or 163.24 (for the double). Nevertheless, you are far ahead when you use Fix-It in a case like this — particularly because the solution of providing an initializer does not require creating a separate initializer function. The error message is correct (and creating an initializer called init could solve the problem), but there is this simpler solution: just set a default value to the variable.

Folding and Unfolding Code

As you browse through your code in Xcode or in a playground, you can hone in on areas you’re concerned with by folding and unfolding the sections of code you’re not interested in at the moment. Folding and unfolding affects the display only: The code is still there. Folded code will be compiled.

Folding and unfolding is available for syntactic elements of code. Figure 3-8 shows part of application(_:didFinishLaunchingWithOptions:) at the top of AppDelegate.swift in the example app.

image

Figure 3-8: “Fold up” code you don't need to look at.

Move the pointer over the code. As you pass over the function, the rest of the code is shown with a gray background so that the function itself is made more prominent. At the top and bottom of the function (lines 17 and 29), small arrows appear in the margin. Click either arrow to fold up the function. When folded up, the function will appear as shown in Figure 3-9. Note the small arrow in the gutter at line 17.

image

Figure 3-9: Folded-up code saves space and lets you focus on areas of interest.

Folding isn’t limited to functions. You can fold up almost any syntactic element: if, switch, or any of the loop constructs.

There are a number of indications that code is folded up. For example, the yellow ellipsis (a series of three dots, as in . . .) that appears in Line 17 of Figure 3-9 is an indicator of folded-up code.

Also, folded-up code produces a discontinuity in line numbers. If you’ve chosen to show line numbers (an option you can set in the Editing section of the Text Editing tab in Xcode preferences), you can see that the line numbers in this example skip from 17 to 30 because lines 18 to 29 have been folded up.

You can unfold a section by clicking on the arrow in the margin or by double-clicking the ellipsis.

Using Code Snippets

Code completion and Fix-It can both help you speed up your typing and writing of code. Code snippets in the library go even further: They are snippets of code you can just drag into your own code. You can use a snippet as-is, but many have tokens — highlighted areas that you can customize with your own variable names or other customizations.

When you drag snippets with tokens into your code, they almost always generate errors because you haven’t replaced the tokens yet. This is normal.

In addition to the built-in library, you can create your own snippets. Both methods are discussed in the following sections.

Working with built-in code snippets

Here are the steps to use for working with built-in code snippets.

1. If necessary, show the utilities area.

The utilities, navigator, and debug areas all can be shown or hidden independently, so what is visible depends on what you’ve been doing. The trio of buttons at the top right of the toolbar (shown in Figure 3-10) let you show or hide each of these areas.

In order to make the library area as big as possible, you may want to drag the tab bar up, as shown in Figure 3-10.

2. Click Snippets in the tab bar — {}.

3. Enter Swift in the search field at the bottom.

The library contains snippets from several languages, so searching for Swift will make certain you’re working only with the Swift snippets.

4. Select the snippet you want to use (as shown in Figure 3-10).

Information about the snippet is shown.

5. Drag the snippet into your source code and place it where you want, as shown in Figure 3-11.

If there are tokens in the snippet, you may get error messages until you enter your own data.

In addition to replacing tokens, feel free to make any other changes you want to the code. When you’ve dropped a snippet into your code, it becomes part of your code. The fact that it came from a snippet rather than from your own typing doesn't matter.

image

Figure 3-10: Show the utilities area.

image

Figure 3-11: Dragging a snippet into your code.

Creating your own code snippets

You can create your own code snippets and add them to the library. You can create these for any code you commonly use, from copyright notices to any other sections particularly relevant to your work.

Here’s how to create a snippet of your own:

1. If necessary, show the utilities area.

In order to make the library area as big as possible, you may want to drag the tab bar up. (Refer to Figure 3-10.)

2. Click Snippets in the tab bar — {}.

3. Highlight the code you want to create as a snippet and drag it into the library, as shown in Figure 3-12.

Note that Figure 3-12 shows the code of one of the functions in the template being dragged into the library: This is why you can see both the code in the file as well as the code in the process of being dragged.

4. Select the snippet in the library.

Information about the snippet is shown.

5. Click the Edit button in the lower left, as shown in Figure 3-13.

6. Add a good title for the snippet, and, unless the snippet you’re creating is language-independent, like a copyright notice, change the language setting to Swift.

7. Choose a scope from the Completion Scope pop-up menu, as shown in Figure 3-14.

Adding a scope makes your snippets even more useful because it prevents you (or your colleagues) from adding the snippet in illogical places.

Set the language setting before choosing the completion scope. The completion scope choices in the pop-up menu change depending on the language selected.

8. (Optional) Replace the token text, such as the < #myVar# > shown in Figure 3-15.

Token text can be more than one word. Until the token is replaced, your snippet will generate an error — again, this is normal.

Figure 3-16 shows a custom snippet with a token (and the associated errors).

image

Figure 3-12: Creating your own snippet.

image

Figure 3-13: Editing the snippet.

image

Figure 3-14: Setting the completion scope.

image

Figure 3-15: Creating a token in your snippet.

image

Figure 3-16: Using a custom snippet.