If you’re completely new to programming, the concepts and features mentioned on this page may not be especially memorable but rest assured that the playground feature is a big deal. It enables developers to write and test code quickly and is without a doubt one the best features of the Swift programming language.
What is a Swift playground?
The playground is a Swift feature that allows developers to write and test code without building their application. Without the build step, programmers can instantly test whether their written code works as it was intended. It may not be very time consuming to test your small project but as your codebase grows, so does the time required to build and run. Playground simplifies the process of testing small bits of your codebase by running your code immediately after you type a line. Once you are satisfied with the results of the code, you can simply copy it into your swift file.
How to create a Swift playground
File > New > File… > Under “Source” will be the option for “Playground”. You can name the playground anything you would like, but typically it will be your AppName.
Adding code to the playground
As you can see from the screenshot below, the left side of the window is where you type and edit your code, while the right side is what is outputted automatically by the playground.
In our example, we created a simple for-in loop that loops through the numbers 0-30. We added a conditional if statement, which checks that:
- The number is greater than or equal to 10.
- The number is equal to or less than 20.
If the statement is true, the playground will print out the number to the console.
Showing the console
Often times, you will see something happened in the right portion of the playground, but specifics aren’t given, only a vague message stating something has happened X number of times. In our example, it shows (11 times). Since we are printing a message using print(i), this shows up in the console, that is currently hidden from view.
To show the console, we need to click the console toggle switch as indicated in the screenshot below: