An Introduction to Xcode 14 Playgrounds

Before introducing the Swift programming language in the following chapters, it is first worth learning about a feature of Xcode known as Playgrounds. This is a feature of Xcode designed to make learning Swift and experimenting with the iOS SDK much easier. The concepts covered in this chapter can be used when experimenting with many of the introductory Swift code examples in the following chapters.

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 for future reference or as a training tool.

Creating a New Playground

Start Xcode and select the File -> New -> Playground… menu option to create a new Playground. Choose the iOS option on the resulting panel and select the Blank template.

The Blank template is useful for trying out Swift coding. The Single View template, on the other hand, provides a view controller environment for trying out code that requires a user interface layout. The game and map templates provide preconfigured playgrounds that allow you to experiment with the iOS MapKit and SpriteKit frameworks, respectively.

On the next screen, name the playground LearnSwift and choose a suitable file system location into which the playground should be saved before clicking on the Create button.

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

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

Figure 5-1

The panel on the left-hand side of the window (marked A in Figure 5-1) is the Navigator panel which provides access to the folders and files that make up the playground. To hide and show this panel, click on the button indicated by the leftmost arrow. The center panel (B) is the playground editor where the lines of Swift code are entered. The right-hand panel (C) 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 tab bar (D) will contain a tab for each file currently open within the playground editor. To switch to a different file, simply select the corresponding tab. To close an open file, hover the mouse pointer over the tab and click on the “X” button when it appears to the left of the file name.

The button marked by the right-most arrow in the above figure is used to hide and show the Inspectors panel (marked A in Figure 5-2 below), where various properties relating to the playground may be configured. Clicking and dragging the bar (B) upward will display the Debug Area (C), where diagnostic output relating to the playground will appear when the code is executed:

Figure 5-2

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

A 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 adding another line of Swift code so that it reads as follows:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

import UIKit
 
var greeting = "Hello, playground"
 
print("Welcome to Swift")Code language: Swift (swift)

All that the additional line of 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 separators when multiple statements occupy the same line of code.

Note that although some extra code has been entered, nothing yet appears in the results panel. This is because the code has yet to be executed. One option to run the code is to click on the Execute Playground button located in the bottom left-hand corner of the main panel, as indicated by the arrow in Figure 5-3:

Figure 5-3

When clicked, this button will execute all the code in the current playground page from the first line of code to the last. Another option is to execute the code in stages using the run button located in the margin of the code editor, as shown in Figure 5-4:

Figure 5-4

This button executes the line numbers with the shaded blue background, including the line on which the button is currently positioned. In the above figure, for example, the button will execute lines 1 through 3 and stop.

The position of the run button can be moved by hovering the mouse pointer over the line numbers in the editor. In Figure 5-5, for example, the run button is now positioned on line 5 and will execute lines 4 and 5 when clicked. Note that lines 1 to 3 are no longer highlighted in blue, indicating that these have already been executed and are not eligible to be run this time:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 5-5

This technique provides an easy way to execute the code in stages, making it easier to understand how the code functions and to identify problems in code execution.

To reset the playground so that execution can be performed from the start of the code, simply click on the stop button as indicated in Figure 5-6:

Figure 5-6

Using this incremental execution technique, execute lines 1 through 3 and note that output now appears in the results panel, indicating that the variable has been initialized:

Figure 5-7

Next, execute the remaining lines up to and including line 5 at which point the “Welcome to Swift” output should appear both in the results panel and debug area:

Figure 5-8

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:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

var x = 10
 
for index in 1...20 {
    let y = index * x
    x -= 1
    print(y)
}Code language: Swift (swift)

This expression repeats a loop 20 times, performing arithmetic expressions on each iteration of the loop. Once the code has been entered into the editor, click on the run button positioned at line 13 to execute these new lines of code. 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-9:

Figure 5-9

Hovering over the output will display the Quick Look button on the far right, which, when selected, will show a popup panel displaying the results as shown in Figure 5-10:

Figure 5-10

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

Figure 5-11

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 textCode language: plaintext (plaintext)

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

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

/*:
This is a block of documentation text that is intended
to span multiple lines
*/Code language: plaintext (plaintext)

The rich text uses the 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 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 Markup is 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 markup 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 intended to demonstrate:
* The use of **Quick Look**
* Placing results **in-line** with the code
*/Code language: plaintext (plaintext)

As the comment content is added, it is said to be displayed in raw markup format. To display in rendered markup format, either select the Editor -> Show Rendered Markup menu option or enable the Render Documentation option located under Playground Settings in the Inspector panel (marked A in Figure 5-2). If the Inspector panel is not currently visible, click on the button indicated by the right-most arrow in Figure 5-1 to display it. Once rendered, the above rich text should appear as illustrated in Figure 5-12:

Figure 5-12

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

https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/ index.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 a page to the playground now by selecting the LearnSwift entry at the top of the Navigator panel, right-clicking, and selecting the New Playground Page menu option. If the Navigator panel is not currently visible, click the button indicated by the left-most arrow in Figure 5-1 above to display it. 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-13:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 5-13

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

Working with UIKit in Playgrounds

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

When working with UIKit within a playground page, we first need to import the iOS UIKit Framework. The UIKit Framework contains most of the classes required to implement user interfaces for iOS apps and is an area that will be covered in considerable detail throughout the book. A compelling feature of playgrounds is that it is possible to work with UIKit and many other frameworks that comprise the iOS 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)
myLabelCode language: Swift (swift)

Enter this code into the playground editor on the UIKit Examples page (the existing code can be removed) and run the code. This code provides an excellent demonstration of how the Quick Look feature can be helpful.

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Each line of the example Swift code configures a different aspect of the appearance of the UILabel instance. For example, clicking 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:

Figure 5-14

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:

Figure 5-15

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

Figure 5-16

Adding Resources to a Playground

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

Figure 5-17

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

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

https://www.ebookfrenzy.com/web/ios16/

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:

Figure 5-18

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")Code language: Swift (swift)

With the code added, run the new statement and use either the Quick Look or inline option to view the results of the code:

Figure 5-19

Working with Enhanced Live Views

So far in this chapter, all UIKit examples have presented static user interface elements using the Quick Look and inline features. It is, however, also possible to test dynamic user interface behavior within a playground using the Xcode Enhanced Live Views feature. First, create a new page within the playground named Live View Example to demonstrate live views in action. Then, 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:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

import UIKit 
import PlaygroundSupportCode language: Swift (swift)

The PlaygroundSupport module provides several useful playground features, including 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
})Code language: Swift (swift)

The code creates a UIView object as a container view and assigns it a white background color. A smaller view is then drawn and positioned in the center of the container view and colored red. The second view is then added as a child of the container view. Animation is then used to change the smaller view’s color to blue and rotate it 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 provided to highlight the capabilities of live views.

Once the code has been executed, 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. Therefore, the live view playground feature will be necessary to see how the animation code works.

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. 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 enable the timeline, enable the Xcode Editor -> Live View menu option as shown in Figure 5-20:

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 5-20

Once the timeline is enabled, 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
})Code language: Swift (swift)

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

Figure 5-21

To repeat the execution of the code on the playground page, click on the stop button highlighted in Figure 5-6 to reset the playground and change the stop button into the run button (Figure 5-3). Then, click the run button to repeat the execution.

When to Use Playgrounds

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 is recommended.

It is also essential to remember 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.

 

You are reading a sample chapter from iOS 16 App Development Essentials.

Buy the full book now in eBook or Print format.

The full book contains 93 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

The iOS SDK is a vast collection of frameworks and classes. As a result, it is not unusual for even experienced developers 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, and run cycle to arrive at a programming solution. Rather than fall into this habit, consider having a playground on standby to conduct 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 are viewed dynamically. This provides an excellent environment for learning the Swift programming language and experimenting with many of the classes and APIs included in the iOS SDK without creating Xcode projects and repeatedly editing, compiling, and running code.