An Introduction to Swift Playgrounds

PreviousTable of ContentsNext
A Guided Tour of XcodeSwift Data Types, Constants and Variables


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


Before introducing the Swift programming language in the chapters that follow, it is first worth learning about a feature of Xcode known as Playgrounds. Playgrounds are a feature introduced in Xcode 6 that make learning Swift and experimenting with the iOS SDK much easier. The concepts covered in this chapter can be put to use when experimenting with many of the introductory Swift code examples contained in the chapters that follow and will be of continued use in future when experimenting with many of the features of UIKit framework when designing dynamic user interfaces.

What is a Playground?

A playground is an interactive environment where Swift code can be entered and executed with the results appearing in real-time. This makes an ideal environment in which to learn the syntax of Swift and the visual aspects of iOS app development without the need to work continuously through the edit/compile/run/debug cycle that would ordinarily accompany a standard Xcode iOS project. With support for rich text comments, playgrounds are also a good way to document code as a teaching environment.

Creating a New Playground

To create a new Playground, start Xcode and select the Get started with a playground option from the welcome screen or select the File -> New -> Playground menu option. On the resulting options screen, name the playground LearnSwift and set the Platform menu to iOS. Click Next and choose a suitable file system location into which the playground should be saved.

Once the playground has been created, the following screen will appear ready for Swift code to be entered:

A new Swift Playground

Figure 5-1

The panel on the left-hand side of the window (marked A in Figure 5 1) is the playground editor where the lines of Swift code are entered. The right-hand panel (marked B) is referred to as the results panel and is where the results of each Swift expression entered into the playground editor panel are displayed.

The cluster of three buttons at the right-hand side of the toolbar (marked C) are used to hide and display other panels within the playground window. The left most button displays the Navigator panel which provides access to the folders and files that make up the playground (marked A in Figure 5 2 below). The middle button, on the other hand, displays the Debug view (B) which displays code output and information about coding or runtime errors. The right most button displays the Utilities panel (C) where a variety of properties relating to the playground may be configured.


the key areas of a the Xcode Swift playground interface

Figure 5-2


By far the quickest way to gain familiarity with the playground environment is to work through some simple examples.

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


A Basic Swift Playground Example

Perhaps the simplest of examples in any programming language (that at least does something tangible) is to write some code to output a single line of text. Swift is no exception to this rule so, within the playground window, begin by deleting the current Swift expression from the editor panel:

var str = “Hello, playground”

Next, enter a line of Swift code that reads as follows:

print("Welcome to Swift")

All that the code does is make a call to the built-in Swift print function which takes as a parameter a string of characters to be displayed on the console. Those familiar with other programming languages will note the absence of a semi-colon at the end of the line of code. In Swift, semi-colons are optional and generally only used as a separator when multiple statements occupy the same line of code.

Note that after entering the line of code, the results panel to the right of the editing panel is now showing the output from the print call as highlighted in Figure 5-3:


The initial page of a new Swift playground

Figure 5-3

Viewing Results

Playgrounds are particularly useful when working and experimenting with Swift algorithms. This can be useful when combined with the Quick Look feature. Remaining within the playground editor, enter the following lines of code beneath the existing print statement:

var x = 10

for index in 1...20 {
        let y = index * x
        x -= 1
}

This expression repeats a loop 20 times, performing an arithmetic expression on each iteration of the loop. Once the code has been entered into the editor, the playground will execute the loop and display in the results panel the number of times the loop was performed. More interesting information, however, may be obtained by hovering the mouse pointer over the results line so that two additional buttons appear as shown in Figure 5-4:


Playground results panel buttons

Figure 5-4

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

The left most of the two buttons is the Quick Look button which, when selected, will show a popup panel displaying the results as shown in Figure 5-5:


The Xcode 8 playground quick look panel

Figure 5-5


The right-most button is the Show Result button which, when selected, displays the results in-line with the code:


Viewing a value history in a Swift playground

Figure 5-6

Enabling the Timeline Slider

A useful tool when inspecting the results of a code sequence is the timeline slider. Switched off by default, the slider can be enabled by displaying the Utilities panel (Marked C in Figure 5-2) and enabling the Show Timeline check box as illustrated in Figure 5-7:


Enabling the Swift Playground timeline slider

Figure 5-7


Once enabled, the timeline appears as a slider located along the bottom edge of the playground panel and can be moved to view the prevailing results at different points in the value history. Sliding it to the left, for example, will highlight and display the different values in the graph:


Using the Swift Playground Timeline Slider

Figure 5-8


Clicking on the blue run button located to the left of the timeline slider will re-run the code within the playground.

Adding Rich Text Comments

Rich text comments allow the code within a playground to be documented in a way that is easy to format and read. A single line of text can be marked as being rich text by preceding it with a //: marker. For example:

//: This is a single line of documentation text

Blocks of text can be added by wrapping the text in /*: and */ comment markers:

/*: 
This is a block of documentation text that is intended
to span multiple lines 
*/

The rich text uses the Markdown markup language and allows text to be formatted using a lightweight and easy to use syntax. A heading, for example, can be declared by prefixing the line with a ‘#’ character while text is displayed in italics when wrapped in ‘*’ characters. Bold text, on the other hand, involves wrapping the text in ‘**’ character sequences. It is also possible to configure bullet points by prefixing each line with a single ‘*’. Among the many other features of Markdown are the ability to embed images and hyperlinks into the content of a rich text comment.

To see rich text comments in action, enter the following markdown content into the playground editor immediately after the print(“Welcome to Swift”) line of code:

/*:
# Welcome to Playgrounds
This is your *first* playground which is intented to demonstrate:
* The use of **Quick Look**
* Placing results **in-line** with the code
*/

As the comment content is added it is said to be displayed in raw markup format. To display in rendered markup format, select the Editor -> Show Rendered Markup menu option. Once rendered, the above rich text should appear as illustrated in Figure 5-9:


Rendered markup in a Swift playground

Figure 5-9


Detailed information about the Markdown syntax can be found online at the following URL:

https://developer.apple.com/library/ios/documentation/Swift/Reference/Playground_Ref/Chapters/MarkupReference.html

Working with Playground Pages

A playground can consist of multiple pages, with each page containing its own code, resources and rich text comments. So far, the playground used in this chapter contains a single page. Add an additional page to the playground now by selecting the File -> New -> Playground Page menu option. Once added, click on the left most of the three view buttons (marked C in Figure 5 1) to display the Navigator panel. Note that two pages are now listed in the Navigator named “Untitled Page” and “Untitled Page 2”. Select and then click a second time on the “Untitled Page 2” entry so that the name becomes editable and change the name to UIKit Examples as outlined in Figure 5-10:


A new pages added to a Swift Playground

Figure 5-10


Note that the newly added page has Markdown links which, when clicked, navigate to the previous or next page in the playground.

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Working with UIKit in Playgrounds

The playground environment is not restricted to simple Swift code statements. Much of the power of the iOS 10 SDK is also available for experimentation within a playground.

When working with UIKit within a playground page it is necessary to import the iOS UIKit Framework. The UIKit Framework contains most of the classes necessary to implement user interfaces for iOS applications and is an area which will be covered in significant detail throughout the book. An extremely powerful feature of playgrounds is that it is also possible to work with UIKit along with many of the other frameworks that comprise the iOS 10 SDK.

The following code, for example, imports the UIKit framework, creates a UILabel instance and sets color, text and font properties on it:

import UIKit

let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))

myLabel.backgroundColor = UIColor.red
myLabel.text = "Hello Swift"
myLabel.textAlignment = .center
myLabel.font = UIFont(name: "Georgia", size: 24)
myLabel

Enter this code into the playground editor on the UIKit Examples page (the line importing the Foundation framework can be removed) and note that this is a good example of how the Quick Look feature can be useful. Each line of the example Swift code configures a different aspect of the appearance of the UILabel instance. Clicking on the Quick Look button for the first line of code will display an empty view (since the label exists but has yet to be given any visual attributes). Clicking on the Quick Look button in the line of code which sets the background color, on the other hand, will show the red label:


A blank label within a Swift playground

Figure 5-11


Similarly, the quick look view for the line where the text property is set will show the red label with the “Hello Swift” text left aligned:


Xcode 8 playground label text.png

Figure 5-12

The font setting quick look view on the other hand displays the UILabel with centered text and the larger Georgia font:


A label within a Swift playground

Figure 5-13

Adding Resources to a Playground

Another feature of playgrounds is the ability to bundle and access resources such as image files in a playground. Within the Navigator panel, click on the right facing arrow to the left of the UIKit Examples page entry to unfold the page contents (Figure 5-14) and note the presence of a folder named Resources:


Adding resources to a Swift Playground

Figure 5-14


If you have not already done so, download and unpack the code samples archive from the following URL:

http://www.ebookfrenzy.com/web/ios10/

Open a Finder window, navigate to the playground_images folder within the code samples folder and drag and drop the image file named waterfall.png onto the Resources folder beneath the UIKit Examples page in the Playground Navigator panel:


An image added to a Swift Playground

Figure 5-15


With the image added to the resources, add code to the page to create an image object and display the waterfall image on it:

let image = UIImage(named: "waterfall")

With the code added, use the Quick Look option to view the results of the code:


Using the Playground Quick Look option to display an image

Figure 5-16

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Working with Enhanced Live Views

So far in this chapter, all of the UIKit examples have involved presenting static user interface elements using the Quick Look and in-line features. It is, however, also possible to test dynamic user interface behavior within a playground using the Xcode Enhanced Live Views feature. To demonstrate live views in action, create a new page within the playground named Live View Example. Within the newly added page, remove the existing lines of Swift code before adding import statements for the UIKit framework and an additional playground module named PlaygroundSupport:

import UIKit
import PlaygroundSupport

The XCPlayground module provides a number of useful features for playgrounds including the ability to present a live view within the playground timeline. Beneath the import statements, add the following code:

import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0,y: 0,width: 200,height: 200))
container.backgroundColor = UIColor.white
let square = UIView(frame: CGRect(x: 50,y: 50,width: 100,height: 100))
square.backgroundColor = UIColor.red

container.addSubview(square)

UIView.animate(withDuration: 5.0, animations: {
    square.backgroundColor = UIColor.blue
    let rotation = CGAffineTransform(rotationAngle: 3.14)
    square.transform = rotation
})

The code creates a UIView object to act as a container view and assigns it a white background color. A smaller view is then drawn positioned in the center of the container view and colored red. The second view is then added as a child of the container view. An animation is then used to change the color of the smaller view to blue and to rotate it through 360 degrees. If you are new to iOS programming rest assured that these areas will be covered in detail in later chapters. At this point the code is simply provided to highlight the capabilities of live views.

Clicking on any of the Quick Look buttons will show a snapshot of the views at each stage in the code sequence. None of the quick look views, however, show the dynamic animation. To see how the animation code works it will be necessary to use the live view playground feature.

The PlaygroundSupport module includes a class named PlaygroundPage that allows playground code to interact with the pages that make up a playground. This is achieved through a range of methods and properties of the class, one of which is the current property. This property, in turn, provides access to the current playground page. In order to execute the live view within the playground timeline, the liveView property of the current page needs to be set to our new container. To display the timeline, click on the toolbar button containing the interlocking circles as highlighted in Figure 5-17:


Displaying the Swift Playground Assistant Editor

Figure 5-17

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

When clicked, this button displays the Assistant Editor panel containing the timeline. Once the timeline is visible, add the code to assign the container to the live view of the current page as follows:

import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0,y: 0,width: 200,height: 200))

PlaygroundPage.current.liveView = container

container.backgroundColor = UIColor.white
let square = UIView(frame: CGRect(x: 50,y: 50,width: 100,height: 100))
square.backgroundColor = UIColor.red

container.addSubview(square)

UIView.animate(withDuration: 5.0, animations: {
    square.backgroundColor = UIColor.blue
    let rotation = CGAffineTransform(rotationAngle: 3.14)
    square.transform = rotation
})

Once the call has been added, the views should appear in the timeline (Figure 5-18). During the 5 second animation duration, the red square should rotate through 360 degrees while gradually changing color to blue:


Animation within a Swift Playground

Figure 5-18


To repeat the execution of the code in the playground page, select the Editor -> Execute Playground menu option or click on the blue run button located next to the timeline slider. If the square stop button is currently displayed in place of the run button, click on it to stop execution and redisplay the run button. The different stages of the animation may also be viewed by moving the timeline slider located along the bottom edge of the playground window. Since the animation only lasts 5 seconds the length of time covered by the slider may also be reduced to 5 seconds using the control located at the end of the slider:


The Swift Playground timeline slider

Figure 5-19

When to Use Playgrounds

Clearly Swift Playgrounds provide an ideal environment for learning to program using the Swift programming language and the use of playgrounds in the Swift introductory chapters that follow is recommended.

It is also important to keep in mind that playgrounds will remain useful long after the basics of Swift have been learned and will become increasingly useful when moving on to more advanced areas of iOS development.

The iOS 10 SDK is a vast collection of frameworks and classes and it is not unusual for even experienced developers to need to experiment with unfamiliar aspects of iOS development before adding code to a project. Historically this has involved creating a temporary iOS Xcode project and then repeatedly looping through the somewhat cumbersome edit, compile, run cycle to arrive at a programming solution. Rather than fall into this habit, consider having a playground on standby to carry out experiments during your project development work.

Summary

This chapter has introduced the concept of playgrounds. Playgrounds provide an environment in which Swift code can be entered and the results of that code viewed dynamically. This provides an excellent environment both for learning the Swift programming language and for experimenting with many of the classes and APIs included in the iOS 10 SDK without the need to create Xcode projects and repeatedly edit, compile and run code.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
A Guided Tour of XcodeSwift Data Types, Constants and Variables