Messing Around in a Playground

We’ll start getting a feel for programming for iOS in what Xcode calls a playground, so click the “Get started with a playground” button. This brings up a new window, with a sheet showing two options for the playground: a name (defaulting to MyPlayground) and a platform. Make sure the platform is set to iOS, accept the default name, and click Next. Now we have to choose a destination folder to store the playground file. Anything will do here—Desktop, Documents, whatever—so pick something and click Create.

This brings up a window like the figure, with a toolbar and status pane at the top, a source editor on the left, an empty pane on the right, and a play/stop button at the bottom. For a moment, the status indicator will say Running MyPlayground…, and then the text "Hello, playground" will appear in the right pane, directly across from the source code line var str = "Hello, playground" (if you can’t see it, the right pane may be too narrow; resize it by dragging the divider to the left).

images/playing/playground-default.png

What’s happening here is that the playground is an interactive environment for writing and running small snippets of code. Anything we type in will be immediately executed—as long as it’s valid code—and the results shown on the right side. By default, there is a single line of code that creates a string ("Hello, playground") and assigns it to the variable str. The result of this assignment is also the return value, which is why it shows up in the results pane.

Well, two can play at that game, right? On a new line at the bottom, let’s write something really simple:

 var​ two = 1 + 1

After a moment, the number 2 appears in the results pane.

Great, now we can do some math. Let’s add another line to use that result:

 two = two * two

As we expect, the number 4 appears in the results pane.

That’s all well and good, but it’s not much better than we could achieve with a calculator, or even by punching mathematical expressions into the Spotlight search bar. Let’s think of something a little more ambitious.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset