Swift Playgrounds

For this chapter, we shall look at this brilliant new feature called Playground. You can simply type the code you see in this chapter in a Playground, and it will run and show the results without having to compile or run the application. However, there are a few things to note before we start:

  • The language supported by Playgrounds is a new language called Swift, introduced by Apple. You cannot have (as yet) a Playground with Objective-C as the code language.
  • The entire file is a single Playground and called so too. This means that the compiler treats it like a single source file. This can give rise to issues where, for example, if you used a variable called temp as string, and further down you used it as an int, the compiler would throw an error complaining that the variable is being redefined.
  • The code you can type in a Playground is specific to the platform of the Playground, that is, iOS or OS X. This affects the code in terms of the classes available for use, CocoaTouch or Cocoa. If your Playground is for iOS, you cannot have the classes that are available for Mac OS X, and vice-versa.
  • The code is compiled and run at every change as you type/alter the code. The results could vary from machine to machine, depending on the specs of the Mac you are running it on.

Note

You can open only one Playground at a time.

The UI

We can create a new Playground by navigating to File | New | Playground or by OPT + CMD + N:

The UI

The Playground is the Xcode editor without the toolbar, or the other elements. It has a sidebar that displays the results of the line of code. It is suggested that you turn on the assistant editor as it displays additional information that would be quite useful:

The UI

If you hover over the results in the main code editor, you see two icons, an eye and a circle. The eye allows you to view the value in a pop-up, if it is a primitive, such as Int, String, and Double, it will display the value. If it is a complex class such as CGRect, CGPoint, UIBezierCurve, and UIColor, it is displayed visually, as in the following screenshot:

The UI

Playgrounds can show a lot of information that is otherwise difficult to visualize. For the simplest amazing example to illustrate this point, type the following code in a Playground to see the results:

var red = UIColor.redColor()
var rect1 = CGRectMake(10, 10, 200, 50)
var path = UIBezierPath(ovalInRect:rect1)

The following screenshot shows the Playground:

The UI

Tip

The items in the sidebar can be added by simply hovering over the line and clicking on the + icon. If the item is displayed, the icon shows as a filled circle, as shown in the preceding screenshot.

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

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