← Back to Swift Course | Chapter 1: Setup & Basics | Lesson 3 of 7

Swift Playgrounds

A playground is a special sandbox where you can type Swift code and instantly see what it does, without building a whole app.

What a Playground Is

A Swift playground is an interactive scratchpad, built into Xcode and the standalone Swift Playgrounds app, where each line of code runs and shows its result immediately in a sidebar. It is designed for quickly experimenting with ideas without creating a full project.

Example: What a Playground Is

markup
let message = "Playgrounds show results instantly"
print(message)

Command-Line Scripts as a Playground Alternative

Outside of Xcode, a plain .swift file run with the swift command gives similar fast feedback: write top-level statements and run the file to see printed output immediately, which is exactly how the examples in this course work.

Note: Every example in this course can be run this same way: save it as a .swift file and run swift filename.swift.

Example: Command-Line Scripts as a Playground Alternative

markup
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled)

Good Uses for a Playground

Playgrounds are best for testing a small piece of logic, exploring a new API, or checking how a language feature behaves before committing it to a larger codebase, since you get instant visual feedback without the overhead of building a full app.

Example: Good Uses for a Playground

markup
for n in 1...5 {
    print("Testing square of \(n): \(n * n)")
}
Common Mistakes
  1. Believing playgrounds are required to write Swift; they are a convenience tool, not a mandatory step.
  2. Writing performance-heavy code in a playground and being confused when it runs slower than a compiled app -- playgrounds interpret code line by line for live feedback.
  3. Forgetting that playground-only APIs like PlaygroundPage.current don't exist in a normal compiled command-line program.
Chapter Summary
  • Playgrounds are interactive Swift environments available in Xcode and the Swift Playgrounds app.
  • They show the result of each line immediately, which is great for learning and experimenting.
  • Command-line .swift scripts (run via swift file.swift) give similar instant feedback without needing Xcode.
  • Playgrounds are ideal for testing small snippets before adding them to a real project.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.