Playing in the Playground - Getting Started with Swift - Swift For Dummies (2015)

Swift For Dummies (2015)

Part I. Getting Started with Swift

Chapter 2. Playing in the Playground

In This Chapter

arrow Trying out code in a playground

arrow Spotting syntax errors in a playground

arrow Observing values as code runs

One of the important features of Swift and Xcode 6 is the playground, a tool that you can use to experiment with syntax and code to get immediate response. You’ll use playgrounds frequently in the exercises in this book to explore snippets of syntax.

You can build a playground for a section of code that you want to test repeatedly, but you can also create a playground to test code on the fly. When your test is complete, you can keep the playground or just throw the playground away.

This chapter provides an overview of playgrounds. Stepping through the examples in this chapter can help you get the hang of playgrounds and allow you to explore some basic Swift snippets.

Some of the snippets in this chapter have syntax errors in them. This is deliberate. The purpose of this is to demonstrate the way Xcode deals with typos. Somewhere in the universe there may be a place where software engineers always write error-free code, but Planet Earth apparently isn’t it. It’s easy to introduce errors — by, say, reversing the order of key-value items in your code (a problem made easier by the fact that Objective-C has a syntax element that lets you specify key-value properties in a value-key sequence and another syntax element that lets you specify key-value properties in a key-value sequence).

Creating a Playground

Playgrounds are part of Xcode. You can use and reuse a single playground as a scratchpad or you can create a variety of unique playgrounds to test various features of your app. The choice is yours.

icon tip In my case, I keep my playgrounds in a Playgrounds folder on my desktop. At the root level of this folder I keep a few playgrounds lying around. I commonly use the convention of adding “Junk” to the name of any playground or file I don’t want to keep, and I can always find a few “Junk” playgrounds in that folder. Within Playgrounds, I also keep a folder or two for current projects. On occasion I’ve created a Playgrounds folder within a project folder, but the desktop folder works better for me — in my view, playgrounds are just scratchpads, and are more related to the computer I’m using than to the project I’m working on. (For similar reasons, I tend not to include playgrounds among the project files I share with colleagues. Who shares scratchpads?) I prefer to place playgrounds where they won’t get stored in Git, and this suggests to me the desktop folder. However, this is just me. You should use whatever is easiest for you.

Here are the steps to create a playground:

1. Click File⇒New⇒Playground (or just click Shift-Option-appleinline -N).

The sheet shown in Figure 2-1 appears.

image

Figure 2-1: Creating a playground.

2. Name your playground and choose iOS or OS X as the platform.

3. On the next screen, choose the location for your playground.

As noted earlier, you can place your playgrounds in a standard location (like my Playgrounds folder) or you can place them within your specific project folders (or anywhere else you like).

That’s all there is to creating a playground. Figure 2-2 shows a playground created for iOS. Note that if you have created a playground for OS X, the only difference is that it will import Cocoa rather than UIKit.

image

Figure 2-2: A newly created playground.

The basic playground that you create has a comment at the top and a single import statement. Following that is a line of Swift code:

var str = "Hello, playground"

icon tip Note that in the panel to the right of the code, the value of str appears. This is the value as it was set in the main body of the playground. This will be very important as you move through this chapter.

Using a Playground

You may not have explored any Swift syntax yet, but you can still experiment with it. In the following sections, I show you how to test the results of a line of code in a playground, and then how to check the syntax of your code within a playground.

Testing a line of code

The results of any code you type into the playground can be seen more or less instantly. To illustrate, begin with the playground I created in the previous section, the one shown in Figure 2-2. Then change the value of str with these steps:

1. Add a line to change the value of str to “Another String” as shown in Figure 2-3.

2. Look at the sidebar to see the new value.

The original value of str, “Hello, playground,” is now changed to “Another String.”

image

Figure 2-3: Changing the value of a variable in a playground.

This is the pattern for using playgrounds in Swift: Just type something in the playground and see the new result in the sidebar. The result in the sidebar may or may not be what you were looking for, but you can still respond accordingly, as follows:

· If the value is what you expect, you’re done (and you’re successful!).

· If nothing changes in the sidebar (that is, if no value appears or if the original value there remains unchanged), check for a syntax error. If the playground can’t interpret your code, it’s not going to execute it.

· If you see the wrong result, check your code. A flaw in logic may have given you the wrong answer.

Depending on your Mac’s processor speed, the other apps or processes you have running, and the complexity of your code, there may be a delay while Swift parses and then executes the code. At least in early versions of playgrounds in Xcode 6, some developers reported that it was sometimes necessary to give the playground a little nudge. Changing your code a little (such as deleting a word or two and then adding it back in) may cause the parser to be reinvigorated.

Checking syntax

One of the best things to do with a playground is to check Swift syntax quickly. Here’s an example of that kind of use. (Note that it involves a deliberate typo.)

This is a demonstration of playgrounds, so don’t worry too much about the syntax here. The Swift syntax (good and bad) shown here will be discussed more fully in Chapter 6.

Swift is type-safe, which means that it requires you to explicitly do your own type conversions. How do you convert an integer to a string? This is a simple task, but if you’re familiar with several languages, it’s easy to forget which language uses which syntax. In such cases, a playground can be very useful: You just open a playground and try a variety of syntax approaches until you get the answer you want. The following steps show you how:

1. Create a playground.

2. Open the Assistant (the two overlapping circles at the top right of the window shown in Figure 2-4).

Listing 2-1 shows the completed code you create in your playground.

This opens a second pane in the playground, just as it does in Xcode editing windows. If you don't see the overlapping circles shown at the top right of Figure 2-4, choose View⇒Show Toolbar.

3. In the main pane (the leftmost pane), type in your first guess at the code.

After the import line and the var line, shown previously in Figure 2-3, I entered:

str = (String)1

If the syntax is incorrect, the playground shows you the errors, as in Figure 2-4. Note that in addition to the errors shown on the right, Xcode offers a Fix-It solution. If your syntax is incorrect, the suggested Fix-It may be wrong (as it is in this case). However, the errors displayed in Console Output at the right of the window show you the actual error: It’s in the conversion to String:

str = (String)1

4. Type in the correct code:

str = String(1)

5. Check the right-hand sidebar to see the result.

The value shown, “1,” is correct. This is the correct number, and the quotes correctly indicate that the value is a string, as shown in Figure 2-5.

6. Verify the result by adding another line.

Here I made the conversion from string to integer by adding

var str2: Int = 1

Check the result in the sidebar, as shown in Figure 2-6.

Note that this new value is an Int and not a String, which you can tell by the absence of quotes.

image

Figure 2-4: Typing in (incorrect) code.

image

Figure 2-5: Testing syntax.

image

Figure 2-6: Check the corrected code.

Listing 2-1: Testing a Playground

// Playground - noun: a place where people can play
import UIKit
var str = String(1)
var str2: Int = 1

Using the Timeline in the Playground

Figure 2-7 shows another example of using a playground. In this case, I tested a for loop. Note that the number of times the loop has iterated appears at the right instead of the values.

image

Figure 2-7: Testing a loop in a playground.

You can track value inside a loop. In Figure 2-8, I’ve changed the loop so that a local variable is set to the value of the counter. Because a value was set in that way, clicking the bull’s-eye icon at the left of the Assistant window, as in Figure 2-8, shows you the value as the loop executes.

image

Figure 2-8: Letting a timeline track values.

What you see at the right of Figure 2-8 is a timeline — a playground feature that graphs your output automatically. The value of j is plotted on the vertical axis, and the value of i is plotted on the horizontal axis. (The notations at the top of the graph show these legends. Because i and j are the same value, this may not be obvious.)

At the bottom of the right pane, dragging the blue line back and forth, as in Figure 2-9, allows you to check specific values. Note that its value — that is, the value of j where you have positioned the indicator — is shown in the small box at the lower-right.

image

Figure 2-9: Testing loop values over time.

Listing 2-2 shows the code as it should be now.

Listing 2-2: Testing a Playground and a Timeline

// Playground - noun: a place where people can play
import UIKit
var str = String(1)
var str2: Int = 1
var j = 0
for var i = 1; i < 200; i++ {
  j = i * 4
}