First Swift Program
In this article, we'll walk through writing your very first Swift program using an environment called Playground. We'll write a simple code to display "Hello Swift!" and run it together.
Launching Playground
Playground is a development environment where we can quickly write Swift code, run it, and see the results. It's very useful for learning the Swift language.
We can launch Playground from Xcode. Since Xcode is also required for iOS development, make sure to install it from the App Store if you haven't already.
To launch Playground, we first need to open a project in Xcode so that the top menu becomes available.
If you already have an existing Xcode project, open that project.
If you don't have a project yet, create a new one by following these steps:
1. Launch Xcode and select Create New Project... from the welcome screen.
2. You can choose any type of project, but for this example select Other → Empty, then click [Next].
3. Enter any project name you like in Project Name, then click [Next].
4. Choose a folder to save the project in, then click [Create]. This will create the project and give you access to the Xcode menu.
Now, let's launch a Playground from Xcode. From the top menu, select File > New > Playground...
Select iOS → Blank, then click [Next].
Enter a file name, choose a location to save it, set Add to: to Don't add to any project or workspace, and click [Create].
A playground file will be created as follows. You can open it directly from Finder by double-clicking the file, without going through Xcode from the next time.
The playground file will automatically open with some default code. The left side is where we write Swift code, and the right sidebar shows the execution results for each line.
Click the button in the lower left corner to run it.
You may see a prompt asking for permission to access other processes for debugging. Enter your username and password, then click [Continue].
If everything runs successfully, you'll see a screen like this:
Writing Your First Swift Program
Now, let's write and run a simple Swift code that displays "Hello Swift!".
Delete the auto-generated code and type the following:
print("Hello Swift!")
The print() function outputs values to the console, and it's one of the most frequently used functions.
Click the button again, and you'll see "Hello Swift!" printed in the debug area at the bottom.
If the debug area doesn't automatically appear, you can open it by selecting [View] > [Debug Area] > [Show Debug Area], or by clicking the "Show the Debug Area" icon in the lower right corner.
That's it — we've successfully written and run our first Swift code in Playground. From here, we'll continue using Playground to practice writing Swift code and checking the results as we go.