Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)


We mentioned the Playground feature earlier—it is a new innovative feature supported in Xcode 6 and higher. It gives you the ability to try any piece of code in Swift, and see the results immediately without the need to compile or run the code. So, imagine that you are learning Swift, or working in a project with Swift, and you need to try some code, and check its result. If you are in Objective-C, you need to create a new project, write the code, build, run, and open the simulator to see the results! Very time consuming, isn't it? I mean, it's time consuming here, in the learning track, but after you master the language, you don't need to use Playgrounds. You may just need to use it in test or to check something. To play with the Playground feature use the following steps:

  1. In Swift and Xcode 6, or higher, just create a new playground (as shown in the following screenshot) or open an existing one by choosing the .playground file in a navigator:

  2. Now, enter Swift code in the .playground file, and enjoy the results in the right-hand side sidebar. Xcode evaluates your code while you type it, and for each statement, Xcode displays the results of it in the right-hand side sidebar.

As you see, each line of code is examined, and its result is shown in the results sidebar, in the right-hand side. Even the for loop statement shows you how many times the entire code was executed. To see the value of any variable, just write it in a separate line, and check its value in the right-hand side sidebar. (Check line 11 in the preceding screenshot).

Another feature of Playground is the value history. In the previous for loop, we have a piece of code that is executed repeatedly, right? But I want to know what is going on in each iteration. Xcode helps you with this by providing the history button in the results sidebar, on the line containing the number of times. Once you click on it, it displays a complete graph (timeline) for the values over the time. In the graph, x axis represents time, and y axis represents the value at this time (this iteration).

Once you click on the circle in the results view, you can see the value of this iteration:

Also, keep in mind that Playground includes the standard editing features of Xcode, such as code completion, error checking, syntax correction, and suggestions.