# Your First Swift Program: Hello World with swiftc, Scripts and Xcode

Source: https://devdocs10.com/articles/swift/swift-first-program  
By Murat Bo · Updated 2026-10-28 · DevDocs10 (https://devdocs10.com)

To write your first Swift program, save the line `print("Hello, world!")` in a file named `hello.swift`, compile it with `swiftc hello.swift -o hello`, and run `./hello` in Terminal. You can also run the same file in one step with `swift hello.swift`, or create a Command Line Tool project in Xcode and press Cmd+R. Below you will find all three ways, what `print()` really does with its separator and terminator, and the fixes for the first errors almost every beginner hits.

> **Difficulty:** Beginner
>
> **Helpful to know first:** A Mac with Xcode or its Command Line Tools installed (or a Swift toolchain on Linux or Windows), and how to open Terminal and move into a folder with `cd`.

## Compile and Run Hello World with swiftc

First check that the compiler is installed. This prints the toolchain version, for example a line containing `Apple Swift version 6.4`. If you get an error instead, follow [installing Xcode and Swift tools](/articles/swift/swift-installing-tools) first.

```bash
swift --version
```

Create a folder such as `hello-swift`, then create a file called `hello.swift` inside it with any plain-text code editor (not a word processor). The whole program is one line:

```swift
print("Hello, world!")
// Output: Hello, world!
```

Output (tested with Swift 6.4):

```text
Hello, world!
```

Now compile the file into a program and run that program:

```bash
swiftc hello.swift -o hello
./hello
```

Terminal shows `Hello, world!`. Here is what each piece does:

- `print` is a function from the Swift standard library. You do not need an `import` to use it.
- `"Hello, world!"` is a string literal. Swift strings use straight double quotes only.
- There is no `main()` function. In a single-file program, statements at the top level of the file run from top to bottom, and the program ends after the last one.
- `swiftc` compiles the file into a native executable. `-o hello` names the output; without it, `swiftc` names the executable after the file, which is also `hello` here.
- `./hello` runs the executable in the current folder. You can run it again and again without recompiling, until you change the source.

## Other Ways to Run the Same Program

### Run the file directly with swift

The `swift` command compiles the file in memory and runs it straight away. Nothing is left on disk, which suits quick experiments.

```bash
# compile and run in one step
swift hello.swift
```

To turn a file into a script you can start by name, put a shebang line first and make the file executable with `chmod +x greet.swift`. After that, `./greet.swift` runs it.

```swift
#!/usr/bin/env swift
print("Hello from a script")
// Output: Hello from a script
```

Output (tested with Swift 6.4):

```text
Hello from a script
```

The catch is speed: the code is compiled again on every run, so startup is slower than running a program built with `swiftc`.

### Try single lines in the REPL

Run `swift repl` to get an interactive prompt. Each line you type is compiled and run immediately, and the REPL shows the type and value of every constant you create. Type `:quit` to leave. For anything longer than a few lines, a file is easier to edit and rerun.

### Use an Xcode Command Line Tool project

1. In Xcode choose File > New > Project.
2. Select the macOS tab, then Command Line Tool, and click Next.
3. Enter a product name, make sure the language is Swift, and save the project.
4. Open `main.swift`. Xcode has already written `import Foundation` and `print("Hello, World!")`.
5. Press Cmd+R. The output appears in the debug console at the bottom of the window, followed by `Program ended with exit code: 0`.

Use this when you want breakpoints, several files, or packages.

### Use a playground

An Xcode playground (File > New > Playground) or the Swift Playgrounds app on iPad and Mac runs code without a separate build step and shows each line's result in a side panel. It is the gentlest place to learn, but it is not how real command-line programs are built. For what Playgrounds can and cannot do, see the [Swift Playgrounds guide](/articles/swift/swift-playgrounds).

| Way | How you start it | Best for | Leaves a program on disk? |
| --- | --- | --- | --- |
| swiftc | `swiftc hello.swift -o hello`, then `./hello` | Programs you run many times | Yes |
| swift script | `swift hello.swift` | Quick tests and small scripts | No |
| REPL | `swift repl` | Checking one expression | No |
| Xcode project | Cmd+R | Debugging, several files | Yes, in Xcode's build folder |
| Playground | Runs as you type or on demand | Learning and seeing values per line | No |

## What print() Really Does

The full declaration of `print` is `print(_ items: Any..., separator: String = " ", terminator: String = "\n")`. It takes any number of values of any type, writes them to standard output with the separator between them, and finishes with the terminator, a newline by default.

```swift
let language = "Swift"
let version = 6

print("Hello", language, version)
print("2026", "10", "28", separator: "-")
print("Loading", terminator: "... ")
print("done")
print("Hello, \(language) \(version)!")
// Output:
// Hello Swift 6
// 2026-10-28
// Loading... done
// Hello, Swift 6!
```

Output (tested with Swift 6.4):

```text
Hello Swift 6
2026-10-28
Loading... done
Hello, Swift 6!
```

Three details are worth remembering. Commas put a space between values, so you do not need to convert numbers to text. A custom terminator keeps the next `print` on the same line. And `\(...)` inserts any value into a string; [string interpolation](/articles/swift/swift-string-interpolation) covers it fully. A bare `print()` prints just the terminator, an empty line.

Because `print` accepts `Any`, it prints optionals with their wrapper. The compiler warns `expression implicitly coerced from 'String?' to 'Any'` on the first call below; unwrap the value or give a default with `??` to print clean text.

```swift
let nickname: String? = "Ada"
print(nickname)
print(nickname ?? "no nickname")
// Output:
// Optional("Ada")
// Ada
```

Output (tested with Swift 6.4):

```text
Optional("Ada")
Ada
```

## Surprises After Hello World: main.swift, @main and Lost Output

### Top-level code only works in main.swift

Running statements at the top level is allowed in a single-file program or in the file named `main.swift`. When you compile two files, say `main.swift` and `Helpers.swift`, a `print` at the top level of `Helpers.swift` fails with `error: expressions are not allowed at the top level`. Move the statement into a function and call that function from `main.swift`.

### @main in a single file needs a flag

Swift also lets you mark a type as the entry point. Compiled with a plain `swiftc hello.swift`, the file below fails with `error: 'main' attribute cannot be used in a module that contains top-level code`, because a single file is treated as top-level code. Build it with `swiftc -parse-as-library hello.swift -o hello` instead.

```swift
@main
struct Hello {
    static func main() {
        print("Hello from @main")
    }
}
// Output: Hello from @main
```

Output (tested with Swift 6.4):

```text
Hello from @main
```

### Output that disappears when the program crashes

In a terminal, `print` output appears line by line. When you send it into a file or a pipe (`./app > log.txt`), it is collected in a buffer first, and a crash throws the buffer away. The program below crashes on purpose with a bad index. Without the `fflush(stdout)` line, `log.txt` stays empty even though the first `print` ran; with it, the file contains "Step 1 done".

```swift
import Foundation

print("Step 1 done")
fflush(stdout)   // write buffered output now
let values = [1, 2, 3]
print(values[values.count])
```

Output (tested with Swift 6.4):

```text
Step 1 done
```

The crash message, `Fatal error: Index out of range`, goes to standard error, so it still shows in the terminal.

> In an iOS or Mac app, `print` output only goes to Xcode's console; users never see it. For logs you can read from a device, use [os.Logger](/articles/swift/swift-logging-os-logger).

## First Errors Beginners Hit and How to Fix Them

### Writing Print with a capital P

Swift names are case-sensitive, so `Print` and `print` are different names.

**Problem:** There is no function called `Print`, so the compiler stops with `error: cannot find 'Print' in scope`. The same message appears when you forget the quotes and write `print(Hello)`: Swift then looks for something named `Hello`.

```swift
Print("Hello, world!")
```

**Fix:** Write the function name in lowercase and keep the text inside double quotes.

```swift
print("Hello, world!")
// Output: Hello, world!
```

Output (tested with Swift 6.4):

```text
Hello, world!
```

This works because `print` is the exact name of the standard library function.

### Curly or single quotes around the text

Code copied from a chat app, a PDF or a word processor often contains typographic quotes. Single quotes come from habits in JavaScript or Python.

**Problem:** Swift only accepts straight double quotes. Curly quotes give `error: unicode curly quote found, replace with '"'`, and single quotes give `error: single-quoted string literal found, use '"'`.

```swift
print(“Hello, world!”)
```

**Fix:** Retype the quotes in a code editor, which never converts them.

```swift
print("Hello, world!")
// Output: Hello, world!
```

Output (tested with Swift 6.4):

```text
Hello, world!
```

The corrected line works because `"` is the only string delimiter Swift understands.

### Joining text and a number with +

The second program most people write prints a message with a number in it.

**Problem:** Swift never turns a number into text on its own, so `+` between a `String` and an `Int` fails with `error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'`.

```swift
let age = 30
print("Age: " + age)
```

**Fix:** Use string interpolation, or pass the values to `print` separated by a comma.

```swift
let age = 30
print("Age: \(age)")
print("Age:", age)
// Output:
// Age: 30
// Age: 30
```

Output (tested with Swift 6.4):

```text
Age: 30
Age: 30
```

Both lines work because interpolation and `print` itself convert the number to text for you.

### Running a file that is not there

Terminal commands run in the current folder, so a typo in the file name or the wrong folder breaks the commands, not the code.

**Problem:** With a misspelled file name, `swiftc` reports `error: error opening input file 'helo.swift' (No such file or directory)`. Running `./hello` before compiling, or from another folder, makes zsh report `no such file or directory: ./hello`.

```bash
swiftc helo.swift -o hello
./hello
```

**Fix:** Move into the folder that contains the file, check the name with `ls`, then compile and run.

```bash
cd hello-swift
ls
swiftc hello.swift -o hello
./hello
```

This works because both commands now find the files they expect in the current folder.

> On a Mac, `xcrun: error: invalid active developer path` means the Command Line Tools are missing or were removed by a macOS update. Run `xcode-select --install` and try again.

## Predict the Output

What does this print? Count the lines carefully.

```swift
print("A", "B", separator: "-", terminator: "")
print("C")
print()
print("D", terminator: "!\n")
```

Output (tested with Swift 6.4):

```text
A-BC

D!
```

**Answer:**

It prints three lines, and the middle one is empty:

```swift
print("A", "B", separator: "-", terminator: "")
print("C")
print()
print("D", terminator: "!\n")
// Output:
// A-BC
//
// D!
```

Output (tested with Swift 6.4):

```text
A-BC

D!
```

The first call joins `A` and `B` with `-` and prints no newline, so `C` continues the same line. `print()` prints only its default terminator, an empty line. The last call replaces the newline with `!` followed by a newline.

## Summary

- A complete Swift program can be one line: `print("Hello, world!")`. Top-level code runs from top to bottom in a single file or in `main.swift`.
- `swiftc hello.swift -o hello` builds a program you run with `./hello`; `swift hello.swift` compiles and runs in one step; Xcode and playgrounds add a debugger and live results.
- `print` takes any values, joins them with `separator` (a space) and ends with `terminator` (a newline).
- Optionals print as `Optional(...)`; unwrap them or use `??` first.
- The first errors are almost always a capital letter, the wrong quotes, `+` between text and a number, or the wrong folder.

Next, store values in names and decide which ones may change: [Swift variables and constants](/articles/swift/swift-variables-constants).
