Skip to main content

Hello World (first programs) · Beginner · 14 min

Hello World in Swift on Linux, macOS and Windows with the Swift package manager

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 (swift:6.4 image) · Swift 6.4.2

You will install Swift 6.4 with swiftly, run a one-line script, create and run an executable package with swift run, and greet the reader by name using an optional from readLine().

On this page

Swift is the language Apple uses for iPhone, iPad, Mac and Apple Watch apps, but it is not an Apple-only language. It is open source, the Swift project publishes toolchains for Linux and Windows, and the same compiler and package manager run on all three. The Swift code in this tutorial runs unchanged on Ubuntu, macOS and Windows. The terminal commands are written for Linux and macOS shells; on Windows you run them in WSL, as the install step explains.

Swift compiles to native machine code, like C or Rust, and is strict about types. Its best-known rule is about missing values: a value that might be absent has a different type, called an optional, and the compiler will not let you use it until you have dealt with the "nothing there" case. You will meet that rule in your first interactive program.

The toolchain you install contains three things you use here: the swift driver, which runs scripts and fronts every other command; the swiftc compiler; and the Swift package manager (SwiftPM), which creates projects, builds them and fetches libraries. Everything was written for Swift 6.4.2.

Step 1 · Install Swift

On Linux and macOS, install Swift with swiftly, the Swift project's own toolchain manager. It installs the newest release into your home directory, and later lets you update or switch versions without sudo.

On Ubuntu, make sure curl is installed:

Bash
sudo apt update
sudo apt install -y curl ca-certificates

Then download swiftly for your processor, unpack it and let swiftly init install itself and the latest Swift toolchain:

Bash
cd "$(mktemp -d)"
curl -O "https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz"
tar zxf "swiftly-$(uname -m).tar.gz"
./swiftly init --quiet-shell-followup
. "${SWIFTLY_HOME_DIR:-$HOME/.local/share/swiftly}/env.sh"
hash -r
  • $(uname -m) is your processor type, such as x86_64 or aarch64, so you get the matching build.
  • swiftly init copies swiftly into your home directory, adds it to your shell's start-up file and downloads the newest Swift release. If it prints a list of system packages Swift needs, install them with the apt-get command it shows, then carry on.
  • The . line loads swiftly's settings into the shell you have open, and hash -r makes the shell forget where it last found swift. New terminals do this on their own.

On a Mac you have two choices. Install Xcode from the App Store or developer.apple.com, which includes Swift and is what you need for iPhone and Mac apps. Or use swiftly, which is lighter if you only want the command line:

Bash
curl -O https://download.swift.org/swiftly/darwin/swiftly.pkg
installer -pkg swiftly.pkg -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --quiet-shell-followup
. "${SWIFTLY_HOME_DIR:-$HOME/.swiftly}/env.sh"
hash -r

On Windows, open your Ubuntu (WSL) terminal and follow the Ubuntu commands above. Every command after this step is written for a Linux or macOS shell (bash or zsh), and many of them, such as printf, < /dev/null, rm -rf and ./hello-bin, do not work as written in PowerShell, so WSL is the simplest way through this tutorial. Swift also has a native Windows toolchain, installed with the winget commands or the .exe installer on swift.org/install/windows; the Swift code is the same there, but the shell commands differ (for example, swiftc writes hello-bin.exe), so try it once you know the basics.

The toolchain is a large download, several hundred megabytes on Linux. If you pay for data by the bundle, start it on Wi-Fi or at a time your plan charges less.

Check it worked

swiftly init ends without an error, and ls "${SWIFTLY_HOME_DIR:-$HOME/.local/share/swiftly}" (or ~/.swiftly on a Mac) shows an env.sh file. On Windows, the same check works inside your WSL terminal.

Troubleshooting

swift: command not found straight after installing means the shell has not loaded swiftly's settings. Open a new terminal, or run the . and hash -r lines again.

Step 2 · Check the toolchain

Ask Swift which version it is:

Bash
swift --version

On Linux and macOS with swiftly, swiftly list shows every toolchain you have installed and marks the one in use:

Bash
swiftly list

A project can ask for a particular version by containing a .swift-version file, and swiftly then uses that version inside the project folder. You do not need one for this tutorial.

Check it worked

swift --version prints something like Swift version 6.4.2 (swift-6.4.2-RELEASE) followed by a Target: line naming your platform, such as x86_64-unknown-linux-gnu. With Xcode on a Mac the first line starts Apple Swift version 6.4.

Step 3 · Run a one-line script

Make a throwaway folder and write a Swift file with a single line in it:

Bash
mkdir -p ~/swift-demo
cd ~/swift-demo
cat > hello.swift <<'SWIFT'
print("Hello, world!")
SWIFT
swift hello.swift

That one line is a complete Swift program:

  • print is a function from the Swift standard library, which every Swift file can use without importing anything. It writes its argument and then a newline.
  • "Hello, world!" is a string literal. Swift strings use double quotes only.
  • There is no semicolon. Swift allows one at the end of a line, but nobody writes it.
  • There is no main function. In a single-file script, code at the top level runs from top to bottom.

swift hello.swift compiles the file in memory and runs it straight away, so it feels like a scripting language. To get a standalone program instead, compile it with swiftc:

Bash
swiftc hello.swift -o hello-bin
./hello-bin

-o hello-bin names the output file. The result is a native program for your operating system and processor.

Check it worked

Both swift hello.swift and ./hello-bin print Hello, world!, and ls shows hello.swift and hello-bin.

Step 4 · Create a package with swift package init

One file is fine for a quick test. Anything bigger is a package: a folder with a manifest that SwiftPM knows how to build, test and share. Create one called hello:

Bash
cd ~/swift-demo
mkdir hello
cd hello
swift package init --type executable
find . -type f -not -path './.git/*' | sort
cat Package.swift
cat Sources/hello/hello.swift

swift package init names the package after the folder it runs in. --type executable asks for a program you can run, rather than a library for other code to use. Swift 6.4 creates these files:

  • Package.swift, the manifest.
  • Sources/hello/hello.swift, the program.
  • Tests/helloTests/helloTests.swift, an empty test using Swift Testing, Swift's built-in test library.
  • .gitignore, which keeps build output out of Git.

The manifest is ordinary Swift code. With the comments trimmed it looks something like this:

Swift
// swift-tools-version: 6.4

import PackageDescription

let package = Package(
    name: "hello",
    targets: [
        .executableTarget(
            name: "hello",
            swiftSettings: [
                .enableUpcomingFeature("ApproachableConcurrency"),
            ],
        ),
        .testTarget(
            name: "helloTests",
            dependencies: ["hello"],
            ...
        ),
    ]
)
  • The first line looks like a comment, but SwiftPM reads it. swift-tools-version: 6.4 says which SwiftPM version the manifest needs. Because it is 6.0 or later, your code is also compiled in Swift 6 language mode, where the compiler checks for data races: two parts of a program changing the same value at once. In Swift 5 mode most of these checks were off or only warnings; in Swift 6 mode they are errors that stop the build. You will not write concurrent code in this tutorial, but this line is why a library written for Swift 5 can produce new errors when you move it to 6.
  • import PackageDescription loads the types the manifest uses.
  • .executableTarget(name: "hello") declares a module that builds into a program. SwiftPM finds its code in Sources/hello by convention.
  • swiftSettings turns on an upcoming language feature that new packages get by default. Leave it as it is.
  • .testTarget is the test module, run with swift test.

The program itself is slightly longer than the script:

Swift
// The Swift Programming Language
// https://docs.swift.org/swift-book

@main
struct hello {
    static func main() {
        print("Hello, world!")
    }
}
  • The two // lines are comments.
  • @main marks the type where the program starts. A package can hold many files, so top-level code is not allowed in them (except in a file named main.swift), and @main tells the compiler where to begin.
  • struct hello declares a type called hello. The template names it after your package; Swift style normally gives types a capital first letter, such as Hello.
  • static func main() is the function Swift calls at start-up. static means it belongs to the type itself, not to a particular value of it.
  • The curly braces hold the bodies, and print is the same function as before.

Check it worked

The find command lists ./.gitignore, ./Package.swift, ./Sources/hello/hello.swift and ./Tests/helloTests/helloTests.swift, plus a file or two inside a hidden .build folder that SwiftPM may already have started. cat Package.swift shows a first line starting // swift-tools-version: 6.4.

Step 5 · Build and run it with swift run

From inside the package folder, build and run in one command:

Bash
swift run
ls -a

The first time, SwiftPM prints progress lines such as Building for debugging... and Build of product 'hello' complete!, then the program prints Hello, world!. Run it again and the build lines are much shorter, because nothing changed.

The build output lives in the hidden .build folder. It is safe to delete, and .gitignore keeps it out of Git. swift run makes a debug build, which compiles faster and is easier to debug. For a faster program, build in release mode and run the result directly:

Bash
swift build -c release
"$(swift build -c release --show-bin-path)/hello"

--show-bin-path prints the folder that holds the built program, so you do not need to know where SwiftPM put it.

Check it worked

The last line of swift run is Hello, world!, ls -a now shows a .build folder, and the release program also prints Hello, world!.

Troubleshooting

error: Could not find Package.swift in this directory or any of its parent directories means you are not inside the package. Run cd ~/swift-demo/hello and try again.

Step 6 · Read a name with readLine and unwrap the optional

Now make the program ask for a name and an age. Replace the contents of Sources/hello/hello.swift:

Bash
cat > Sources/hello/hello.swift <<'SWIFT'
@main
struct hello {
    static func main() {
        print("What is your name?")
        let answer = readLine() ?? ""
        let name = answer.isEmpty ? "friend" : answer
        print("Hello, \(name)!")
        print("\(name) has \(name.count) characters and takes \(name.utf8.count) bytes.")

        print("How old are you?")
        if let line = readLine(), let age = Int(line) {
            print("Next year you will be \(age + 1).")
        } else {
            print("I could not read a whole number, so I will skip that.")
        }
    }
}
SWIFT
printf 'Ada\n30\n' | swift run

The printf ... | part types Ada, Enter, 30, Enter for you. To answer yourself, run swift run on its own.

Line by line:

  • readLine() reads one line from the keyboard and removes the newline. Its type is String?, said "optional string": either a string, or nil when there is nothing left to read (for example, input piped from a file that has ended). The ? in the type is the compiler's reminder that you must handle the nil case.
  • ?? "" is the nil-coalescing operator: use the value on the left if there is one, otherwise the value on the right. After it, answer is a plain String that cannot be nil.
  • let declares a constant, a name whose value never changes. Use var only when it must change. Swift works out the type from the value, so you do not write String.
  • answer.isEmpty ? "friend" : answer picks "friend" if the person pressed Enter without typing.
  • "Hello, \(name)!" is string interpolation: Swift replaces \(...) with the value inside the brackets, which can be any expression, such as age + 1.
  • name.count counts characters as a person sees them, and name.utf8.count counts the bytes used to store the text. They differ for anything outside plain English letters, as the check below shows.
  • if let line = readLine(), let age = Int(line) is optional binding. It runs the first block only if readLine() gave a string and Int(line) could turn it into a whole number. Int("thirty") is nil, not a crash. Inside that block, line and age are ordinary non-optional values.
  • else runs when either step gave nil.

Try a Yoruba name written with an accent. This printf writes Fúnmi with the ú stored as u plus a combining accent, which is how many phone keyboards produce it:

Bash
printf 'Fu\xcc\x81nmi\n' | swift run

Check it worked

The first run ends with Hello, Ada!, Ada has 3 characters and takes 3 bytes. and Next year you will be 31. The second prints Fúnmi has 5 characters and takes 7 bytes.: five characters to a reader, seven bytes in memory. Many languages would report 6 or 7 characters here; Swift counts what you see. It then prints I could not read a whole number, so I will skip that., because there was no second line to read.

Step 7 · Read the optional error beginners hit

The most common first error in Swift is treating an optional as if it were a plain value. Make it happen on purpose, back in the demo folder:

Bash
cd ~/swift-demo
cat > oops.swift <<'SWIFT'
let name: String = readLine()
print("Hello, \(name)!")
SWIFT
swift oops.swift 2> errors.txt < /dev/null || echo "Did not compile, as expected"
cat errors.txt

2> errors.txt saves the compiler's messages to a file, and < /dev/null gives the program empty input. The compiler stops before running anything. It reports something like oops.swift:1: followed by a column, then error: value of optional type 'String?' must be unwrapped to a value of type 'String', and suggests fixes: provide a default with ??, or force-unwrap with !.

Choose ??. Force-unwrapping, readLine()!, compiles, but the program crashes with Fatal error: Unexpectedly found nil the moment there is no input. Fix the file:

Bash
cat > oops.swift <<'SWIFT'
let name: String = readLine() ?? "friend"
print("Hello, \(name)!")
SWIFT
swift oops.swift < /dev/null

Check it worked

The first attempt prints Did not compile, as expected, and errors.txt contains must be unwrapped. After the fix, the program prints Hello, friend!.

Common beginner mistakes

  • Using single quotes for strings. 'hello' is an error in Swift; use "hello".
  • Writing interpolation as "Hello, (name)" or "Hello, $name". Only \(name) works.
  • Putting top-level code in a package file other than main.swift while another file has @main. Keep start-up code inside static func main().
  • Reaching for ! to silence the optional error. It moves the problem from compile time to a crash at run time.
  • Running swift run outside the package folder, or running swift hello.swift on a file inside Sources/ that uses @main and expects the rest of the package.

Step 8 · Know where Swift is used and clean up

Swift is used for:

  • Apple platform apps: iPhone, iPad, Mac, Apple Watch and Apple TV apps, usually with SwiftUI for the interface. The next tutorial in that direction is build your first SwiftUI app.
  • Server-side Swift: web services and APIs on Linux, with frameworks such as Vapor and Hummingbird, often deployed in the official swift Docker images.
  • Command-line tools: SwiftPM itself and swiftly are written in Swift.
  • Shared code: business logic written once in a Swift package and used by an iOS app and a Linux server.

If your users are mostly on Android phones, as in much of Africa, Swift alone does not reach them: you would pair it with Kotlin for Android or choose a cross-platform toolkit. Swift is a strong choice when iPhone users matter or when you want one language on the app and the server.

When you are done, remove the demo folder:

Bash
cd ~
rm -rf ~/swift-demo

To move to a newer Swift release later, or remove a toolchain, use swiftly:

Bash
swiftly update latest
swiftly uninstall 6.4.2

To remove swiftly itself and every toolchain it installed, run swiftly self-uninstall. If you also installed the native Windows toolchain, uninstall it from Settings, Apps.

Check it worked

ls ~/swift-demo reports No such file or directory, and swift --version still prints Swift version 6.4.2 (or Apple Swift version 6.4 with Xcode), because removing a project does not touch the toolchain.

Next steps

  • Build an interface for iPhone: build your first SwiftUI app.
  • Compare the language Android uses for the same job: Hello World in Kotlin.
  • See the older language Swift replaced on Apple platforms: Hello World in Objective-C.
  • Run swift test inside a fresh package and open Tests/helloTests/helloTests.swift to write your first #expect check. The Swift book at docs.swift.org covers optionals and strings in depth.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.