Get Started with Xcode Playgrounds
You can use playgrounds in Xcode to quickly write some Swift code, experiment with new Swift syntax, or work on your Swift algorithms skills. Most of all, playgrounds in Xcode are a great way to learn Swift programming.
In this tutorial, you’ll learn how to get started with playgrounds in Xcode. I’ll give you a brief overview of Xcode playgrounds, so you can quickly get started with Swift programming.
Prerequisites for this tutorial:
- A Mac with macOS and Xcode 8 or higher (Xcode 11 is recommended)
- A bit of free time, to play around with code
Ready? Let’s go.
- Getting Started with Playgrounds
- Run Your Code in Xcode
- See Runtime Values in a Playground
- Further Reading
Getting Started with Playgrounds
Let’s get started with playgrounds in Xcode. Here’s what you do:
- Open Xcode on your Mac
- When the Welcome to Xcode window appears, click on Get started with a playground
If you’re not seeing the Welcome to Xcode window, then simply create a new playground by choosing File -> New -> Playground...
.
The following window appears:
Here’s what you do next:
- Select the Blank template, and make sure that iOS is selected, then click Next
- Give your playground a name, like
SwiftExample
, and save it in a convenient folder, then click Create
You now see this:
You can create four types of playgrounds: a blank Swift file, a Game playground that uses SpriteKit
, a map-based playground that uses MapKit
, a playground with SwiftUI, and a View Controller playground that uses UIKit
. It’s easiest to start with a Blank playground.
Let’s do a quick tour of this playground in Xcode. A few things stand out:
- At the top-left of the window you see some Swift code, in the editor. This editor is where you’ll do most of your programming work.
- At the bottom-left of the window you see the Console (or Debug Area). This is where the output of your code appears.
- On top of the Console you see two buttons: the left one is to show or hide the Debug Area, and the right one (looks like a Play button) is to execute the playground.
- At the right of Xcode you see a sidebar. When your code has run, you (usually) see intermediate results here. For instance, you can inspect the value of variables in your code. The Live View also appears here, where you can see the visual results of your code.
- At the top of Xcode you see a status bar. This simply indicates that your code runs OK, or that it contains errors. And at the top-right of the screen you see a few buttons. You can show and hide some of Xcode’s panes and inspectors with it.
OK, now go ahead and run the Swift code in the editor. Simply click the Run button at the bottom-right of the playground, and wait for execution to complete.
Xcode now compiles your code, and shows you its result. The default code doesn’t output anything to the Console, but you should be able to see the value of the variable str
in the sidebar on the right of Xcode.
Run Your Code in Xcode
OK, let’s play with some more interesting Swift code in the playground. Here’s how you (manually) reverse an array in Swift:
let names = ["Arthur", "Deep Thought", "Ford", "Humma Kavula", "Marvin", "Slartibartfast", "Trillian", "Zaphod"]
var reversedNames = [String]()
for i in 1...names.count {
reversedNames.append(names[names.count - i])
}
print(reversedNames)
Replace the code in the playground with the above code. Make sure you also include the line import Foundation
at the top of the file.
Now run the code by clicking the Play button! The following output appears in the Console:
["Zaphod", "Trillian", "Slartibartfast", "Marvin", "Humma Kavula", "Ford", "Deep Thought", "Arthur"]
See how the order of the names in the names
array has been reversed? Here’s how that works:
- First, we’re create an array called
names
and fill it with a bunch of strings. We’re also creating an empty array calledreversedNames
. - Then, we’re coding a for loop for the range
1...names.count
. This loop essentially iterates over every string in the array. - Then inside the loop, we’re getting a name from
names
with the codenames[names.count - i]
, and append it to thereversedNames
array. By usingnames.count - i
we’re essentially starting at the end of the array, going back-to-front. - Finally, we’re printing out the items in the
reversedNames
array. This output ends up in the Console.
Awesome!
So, how does that for loop really work?
- First, note that the length of the
names
array is8
. This is the value ofnames.count
. - The for loop runs 8 times, increasing
i
every time it runs, soi
starts at1
and stops after8
(1 to 8 inclusive). - Inside the loop, we use subscript syntax to get an item from the
names
array by its index number. This index isnames.count - i
. - So, for every iteration we’re subtracting
i
fromnames.count
. This value essentially goes from7
to0
. - Because we’re adding the last item from
names
as the first item inreversedNames
– and so forth – thenames
array gets reversed.
We’re reversing the array manually here, for fun and for learning purposes. When you really need to reverse an array, simply use array.reverse()
or array.reversed()
.
See Runtime Values in a Playground
As your code runs, you can inspect the values of variables and constants in the playground. For example, you can check out the different values of names
and reversedNames
in Xcode’s sidebar.
You can even see the different values of names[names.count - i]
inside the for loop. Simply double-click on the small eye icon in the sidebar, next to where it says “8 times”. A gizmo with the different values shows up. (This only works in a playground!)
You can inspect most values with the sidebar:
- Mouse over an item and double-click the eye icon to Quick Look
- Double-click the rectangular button to Show Result inline in your code
Another way is to debug your code is to simply use print()
. Add this line inside the for loop:
print("\(i) - \(names.count - i) --- \(names[names.count - i])")
When you run the playground again, you see how the items are added in reverse order:
1 - 7 --- Zaphod
2 - 6 --- Trillian
3 - 5 --- Slartibartfast
4 - 4 --- Marvin
5 - 3 --- Humma Kavula
6 - 2 --- Ford
7 - 1 --- Deep Thought
8 - 0 --- Arthur
OK, one last thing… Hold the Command
key while clicking on one of the variables in your code. A tiny menu pops up. This works in Xcode, as well as in a playground. You can choose from a few options:
- Jump to Definition will jump to where that variable was first defined in your code
- Show Quick Help will show you information and code documentation about a symbol (variable, function, etc.)
- Callers helps you identify the bits of code that call a particular function
In a playground, you can even run your code up to a particular line. Mouse over to the “gutter”, the line numbers on the left of the editor. A blue play button appears when you hover over a line number. Clicking the Play button on that line will run your code up to that point. That’s super convenient to run your code line-by-line, and see intermediary results!
Further Reading
Playgrounds in Xcode isn’t just helpful to play around with Swift code, but its tools also make understanding your code easier. You can inspect the values of variables as your code runs, and find out what every line of code does.
Want to play with Swift code in Xcode Playgrounds? Check these tutorials:
- Play With Code: Palindromes In Swift
- Play with Code: Converting Roman Numerals with Swift
- Play With Code: Binary Search In Swift
- Playing With Code: Insertion Sort In Swift
- How To: Shuffling An Array In Swift Explained
Want to learn more? Check out these resources: