Hello, World! Your First Swift Program
Tags: swift, programming
Published: 2022-10-13 14:27:22

_This article first appeared on [matteomanferdini.com](https://matteomanferdini.com/swift-hello-world/)_

Learning how to program is not an easy task. But it is straightforward to get started with it following a very simple Swift tutorial.

The very first program everyone writes is called Hello World. It teaches you the basics of creating and running a program in any language.
  
**Use the Hello World example to write your first Swift program**

The first thing you need to learn is how to print something to the _console_, an output text area where you can print any message.

Printing to the console is straightforward, and it works in the same way in most programming languages. It also helps you understand how [comments](https://en.wikipedia.org/wiki/Comment_\(computer_programming\)) work and teaches you how to fix basic errors.

In this article, I will explore different ways of printing to the console in Swift by using the "Hello, world!" [example](https://en.wikipedia.org/wiki/%22Hello,_World!%22_program). This is the text used by most [programming environments](https://en.wikipedia.org/wiki/Integrated_development_environment) when they generate templates for the apps you create.

Apps that only show some text on the screen are the easiest to create and understand. You need to write more code as you develop advanced features for your apps, so it's essential to learn how to print to the console before moving on to anything else.

**Create your first Hello World program using Xcode playgrounds**

A [playground](https://en.wikipedia.org/wiki/Playgrounds_\(Xcode_feature\)) is a file where Swift programs are written. You can do this in any text editor, but Xcode _playgrounds_ also allow you to run programs and see their results.

Create a new playground by selecting _File -> New -> Playground..._ from the Xcode menu.

![Creating a new playground in Xcode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkq2d6j9rtli3e5y7nn9.png)

Choose the _Blank template_ from the _iOS tab._

![Xcode playground templates](https://matteomanferdini.com/wp-content/uploads/2022/06/Xcode-playground-templates.png)

Pick a name for the playground and choose where to save it.

![Saving an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/Saving-an-Xcode-playground.png)

The playground appears with some template code already inside.

![An Xcode playground with the standard template code](https://matteomanferdini.com/wp-content/uploads/2022/06/An-Xcode-playground-with-the-standard-template-code.png)

Now it's time to write something. Delete everything in the playground and type the following code:

```
print("Hello World!")
```

There is only one instruction in this code, which tells the computer to print _"Hello World!"_ to the console.

You don't know if everything works yet, so it is time to run the program and find out.

**Run your first Hello World program in Xcode playgrounds**

Press the play button in the bottom left corner of the playground's window to run the playground.

![The play button to run the code in an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/The-play-button-to-run-the-code-in-an-Xcode-playground.png)

Press the button in the bottom right corner of the playground's window on the same line as the play button to make the _debug area_ appear. You should see the playground's output printed in the debug area.

![The debug area in an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/The-debug-area-in-an-Xcode-playground.png)

You can also run the playground by pressing the play button in the gutter. This is the space on the left of the code where the line numbers are.

![The editor gutter in an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/The-editor-gutter-in-an-Xcode-playground.png)

You can also check the playground's output in the sidebar on the right side of the playground's window. The sidebar contains more information about the playground's output that isn't printed in the debug area when you run the playground.

![The sidebar showing the intermediate results of an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/The-sidebar-showing-the-intermediate-results-of-an-Xcode-playground.png)

**Fix your first Swift error in Xcode playgrounds**

The `print` statement must follow the rules of the Swift syntax. Xcode detects [errors](https://en.wikipedia.org/wiki/Syntax_error) as you type because the [compiler ](https://en.wikipedia.org/wiki/Compiler)complains if mistakes are made.

The compiler stops when an _error_ occurs and displays an error message in the debug area at the bottom of the playground window.

Remove a letter from the `print` statement to see how this works in action.

```
print("Hello World!")
pint("Hello World!")
```

The compiler flags an error for the code. This happens because it doesn't recognize what you are trying to do.

![A syntax error when running code in an Xcode playground](https://matteomanferdini.com/wp-content/uploads/2022/06/A-syntax-error-when-running-code-in-an-Xcode-playground.png)

Add the missing letter to the `print` instruction, and the error disappears. The compiler is happy now.

This error is trivial, so it is straightforward to fix. Your code can still have mistakes if it's not written correctly, no matter how simple it is.

**Annotate your first Hello World program with comments**

A _comment_ is a piece of text in a program that the compiler ignores. You can use comments to annotate code. There are two ways to write comments in Swift:

  1. Any text placed after the`//`characters is a comment until the end of the line.
  2. You can delimit comments by starting with the`/*`characters and ending with `*/`. Any text between these delimiters is part of the comment, which allows the comment to span multiple lines.

```
// This is a comment, ignored by the compiler

print("Hello World!") // You can also write a comment next to an instruction

/* This is also a comment,
which spans multiple lines
and ends only with a
closing delimiter */
```

The hello world program is elementary, and it usually wouldn't need any comments. It is good practice to add comments only to code that is not immediately evident. You should use comments to explain why some code was written and not explain code the reader can easily understand.

You can also make the code itself a comment to temporarily disable it. This is useful when you have some code that you don't want to run but may need to add or restore at a later stage.

```
// print("Hello world")
/*
print("Hello world")
print("Hello world")
*/
```
**Create your first Hello World iOS app in SwiftUI**

Apps are more complex than playgrounds but creating a hello world app is straightforward thanks to the default iOS app template that you get in Xcode.

Create a new iOS app by selecting _File -> New -> Project..._ from the Xcode menu. Choose the _App_ template from the _Application _section in the _iOS_ tab.

![App templates in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/App-templates-in-Xcode.png)

Here are the app settings that you should then select:

  1. Name the app _hello world_.
  2. Choose _None_ for _Team_. You don't need a development team for such a basic app.
  3. Enter the name of either your own company or the company you work for as the organization identifier. Xcode uses this to set the bundle identifier for the app.
  4. Select _SwiftUI_ for the technology used to build the app's user interface. The other one is _UIKit_ which uses an entirely different approach with _storyboards_.
  5. Set _Swift_ for the programming language used to code the app. This is your only option if you use SwiftUI for the user interface. UIKit also works with Objective-C in the background.
  6. Ensure that the Core Data and unit testing options are not selected. You don't need local databases to store the app's data since it's elementary. There is also no need to test the code of such a basic app.

![Options for a new Xcode project](https://matteomanferdini.com/wp-content/uploads/2022/06/Options-for-a-new-Xcode-project.png)

You need to perform quite a lot of configuration, even for a basic iOS app, because Xcode doesn't know what kind of app you are working on.

Finally, check the _Create Git repository on my Mac_ for your project and save it. In our example, this will not make any difference, but it's useful to initialize a [Git](https://en.wikipedia.org/wiki/Git) repository for any project you create since you will likely need it.

![Saving a new Xcode project](https://matteomanferdini.com/wp-content/uploads/2022/06/Saving-a-new-Xcode-project.png)

Now it's time to see what Xcode has created for you in the background.

**Understand the structure of a basic SwiftUI iOS app**

The _hello world_ project has two source code files. You can choose either one of them from the project navigator on the left side of the Xcode editor.

![The project navigator in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/The-project-navigator-in-Xcode.png)

Open the _hello_worldApp.swift_ file and take a look at the code.

{% embed https://gist.github.com/matteom/45610a6914d652d2154f5b7af552bbbd %}

There is quite a lot going on. [SwiftUI](https://matteomanferdini.com/swiftui/) is a complex framework because it uses advanced Swift concepts such as opaque types, property wrappers, and result builders.

You don't need to know about these concepts to understand how everything works. The most important thing you should be aware of is that you are using a _structure_, which is a custom Swift data type, to define the main scene of the app.

The scene handles a group of views of the app. There is only one view, in this case, declared in the _ContentView.swift_ file.

{% embed https://gist.github.com/matteom/bcddd2bc6013aa22f308b429a296d624 %}

The code uses a structure to define the only view of the app. The view contains everything that appears on the screen when you run the app.

The easiest thing to show on the screen is a label with some text. This is the equivalent of printing something to the console.

**Run your first iOS app in the simulator**

There are three ways of running your iOS app: on an iPhone, using a [simulator](https://en.wikipedia.org/wiki/), and/or inside Xcode previews.

You don't need an iPhone to run basic apps. A _simulator_ has all of the essential features of an actual device, and it is much easier to run an app using this.

The first step is to choose the iOS simulator that you want to run the app on. A default simulator is already selected at the top of your Xcode project window. In this case, it is the iPhone 8.

![The default iOS simulator in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/The-default-iOS-simulator-in-Xcode.png)

You can click on the default simulator and choose a custom one from the simulator menu that appears.

![The list of iOD simulators in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/The-list-of-iOD-simulators-in-Xcode.png)

![The run button in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/The-run-button-in-Xcode.png)

The project [builds](https://en.wikipedia.org/wiki/Software_build) itself without errors and then runs the app on the chosen simulator.

![The hello world app running in the iOS simulator](https://matteomanferdini.com/wp-content/uploads/2022/06/The-hello-world-app-running-in-the-iOS-simulator.png)

SwiftUI also allows you to preview the app's appearance without running the app on a simulator. To do this, switch to the _ContentView.swift _file and look at the preview code.

{% embed https://gist.github.com/matteom/d8b85b61f2e9453ea81b0500b99cde3b %}

The code creates a structure that handles the updates of the app's main view to preview them. You can press the resume button at the top right of the preview window to preview the changes.

![The resume button in the Xcode canvas](https://matteomanferdini.com/wp-content/uploads/2022/06/The-resume-button-in-the-Xcode-canvas.png)

The preview simulator is perfectly synchronized with the code of the view. This means that any changes you make to the code in the left panel can be seen in the simulator in the right panel immediately.

![The hello world app in the Xcode canvas](https://matteomanferdini.com/wp-content/uploads/2022/06/The-hello-world-app-in-the-Xcode-canvas-1536x945.png)

**Create your first command-line macOS app**

There is quite a lot of boilerplate code in the iOS version of the _hello world_ app. This happens because you need to define a user interface for the app even though it is simple.

To avoid all of this code, you can instead create a macOS version of the app, which only prints to the console and doesn't require a user interface of any kind whatsoever.

You can create a new macOS app by selecting _File -> New -> Project..._ from the Xcode menu. Choose the _Command Line Tool_ template from the _Application _section in the _macOS_ tab.

![The command line app template in Xcode](https://matteomanferdini.com/wp-content/uploads/2022/06/The-command-line-app-template-in-Xcode.png)

Name the app _hello world mac _and use the same settings for the app's development team, organization identifier, and programming language that you used for the iOS version of the app. Make sure you select Swift as the programming language of the app. The other options are Objective-C, C++, and C.

![The Xcode project options for a command line app](https://matteomanferdini.com/wp-content/uploads/2022/06/The-Xcode-project-options-for-a-command-line-app.png)

Finally, check the _Create Git repository on my Mac_ and save the project.

All the code of the app is in the _main.swift _file. You simply use the `print` statement to print a message to the console as you did when you used the Xcode playgrounds.

```
print("Hello World!")
```

You can run the app in the very same way that you would run its iOS version.

![The output of the command line app in the Xcode console](https://matteomanferdini.com/wp-content/uploads/2022/06/The-output-of-the-command-line-app-in-the-Xcode-console.png)

The app builds and runs on your Mac this time. It prints "Hello World" in the debug area at the bottom of the project window.

**Run Swift code from the Terminal**

The macOS version of the app is a [console application](https://en.wikipedia.org/wiki/Console_application), so you don't have to run it in Xcode only. Xcode provides a _read-eval-print loop_ ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) which is a [command-line interface](https://en.wikipedia.org/wiki/Command-line_interface) that runs from the Terminal.

Open the Terminal app and enter the `swift` command to launch the REPL environment. This is what you should see in the console window if the command line tools are installed correctly in Xcode:

![The swift command in the terminal](https://matteomanferdini.com/wp-content/uploads/2022/06/The-swift-command-in-the-terminal.png)

If the Terminal doesn't recognize the previous command, then the Xcode command-line tools are not installed properly, so go ahead and install them before moving on.

You can now run Swift code directly in the Terminal. Try out the `print` statement again.

![Printing in the Swift REPL](https://matteomanferdini.com/wp-content/uploads/2022/06/Printing-in-the-Swift-REPL.png)

You will get errors if you type invalid code in the console.

![A syntax error in the Swift REPL](https://matteomanferdini.com/wp-content/uploads/2022/06/A-syntax-error-in-the-Swift-REPL.png)

You can quit the Swift REPL by typing one of the following commands in the Terminal: `:exit`, `:quit` or `:q`.

**Run Swift files from the Terminal**

You can also run Swift files directly in the Terminal. Right-click the _hello world mac _folder, press the _Option_ key on your keyboard, and select the _Copy "hello world mac" as Pathname _option from the menu. You will need the folder's path on the disk to access it inside the Terminal.

Next, enter the `cd [path]` command in the Terminal to switch to the app's folder. Paste the project folder's path to replace the `[path]` part of the command.

![A path error in the Terminal](https://matteomanferdini.com/wp-content/uploads/2022/06/A-path-error-in-the-Terminal.png)

The Terminal does not work well with either file or folder path names that contain spaces. The easiest way to get around this is to place all the file and folder names with spaces between double quotes in the path's name.

![Escaping spaces in a path in the Terminal](https://matteomanferdini.com/wp-content/uploads/2022/06/Escaping-spaces-in-a-path-in-the-Terminal.png)

Now you can finally run the main Swift file of the macOS app in the Terminal. Type the `swift main.swift` command in the Terminal.

![Running a Swift command line app in the Terminal](https://matteomanferdini.com/wp-content/uploads/2022/06/Running-a-Swift-command-line-app-in-the-Terminal.png)

You will get errors if the file contains invalid Swift code.

![A syntax error when running a Swift command line app](https://matteomanferdini.com/wp-content/uploads/2022/06/A-syntax-error-when-running-a-Swift-command-line-app.png)

**Create executable files from source files**

You can use the Terminal to create executable files from source files. This is particularly useful when you want to share your work with someone else, but you don't want to give them access to your code.

Access the _hello world mac_ folder in the Terminal the same way you did in the previous section.

Enter the `swiftc main.swift` command in the Terminal. This command creates an executable file with the same name and in the very same folder as the source file.

![Creating an executable file for a Swift command line tool](https://matteomanferdini.com/wp-content/uploads/2022/06/Creating-an-executable-file-for-a-Swift-command-line-tool.png)

You can't create the executable file if the source file contains invalid Swift code.

![A syntax error when creating a Swift executable file](https://matteomanferdini.com/wp-content/uploads/2022/06/A-syntax-error-when-creating-a-Swift-executable-file.png)

You can run the _main.exe_ executable file in the Terminal in two different ways.

1\. Double click the file in the _hello world mac_ folder, and it will automatically run in the Terminal.

![Executing a Swift command line tool by double clicking](https://matteomanferdini.com/wp-content/uploads/2022/06/Executing-a-Swift-command-line-tool-by-double-clicking.png)

2\. Type the `./main` command in the Terminal to run the file manually.

![Executing a Swift command line tool in the Terminal](https://matteomanferdini.com/wp-content/uploads/2022/06/Executing-a-Swift-command-line-tool-in-the-Terminal.png)