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:
sudo apt update
sudo apt install -y curl ca-certificatesThen download swiftly for your processor, unpack it and let swiftly init install itself and the latest Swift toolchain:
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 asx86_64oraarch64, so you get the matching build.swiftly initcopies 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 theapt-getcommand it shows, then carry on.- The
.line loads swiftly's settings into the shell you have open, andhash -rmakes the shell forget where it last foundswift. 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:
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 -rOn 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:
swift --versionOn Linux and macOS with swiftly, swiftly list shows every toolchain you have installed and marks the one in use:
swiftly listA 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:
mkdir -p ~/swift-demo
cd ~/swift-demo
cat > hello.swift <<'SWIFT'
print("Hello, world!")
SWIFT
swift hello.swiftThat one line is a complete Swift program:
printis 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
mainfunction. 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:
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:
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.swiftswift 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-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.4says 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 PackageDescriptionloads the types the manifest uses..executableTarget(name: "hello")declares a module that builds into a program. SwiftPM finds its code inSources/helloby convention.swiftSettingsturns on an upcoming language feature that new packages get by default. Leave it as it is..testTargetis the test module, run withswift test.
The program itself is slightly longer than the script:
// The Swift Programming Language
// https://docs.swift.org/swift-book
@main
struct hello {
static func main() {
print("Hello, world!")
}
}- The two
//lines are comments. @mainmarks 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 namedmain.swift), and@maintells the compiler where to begin.struct hellodeclares a type calledhello. The template names it after your package; Swift style normally gives types a capital first letter, such asHello.static func main()is the function Swift calls at start-up.staticmeans it belongs to the type itself, not to a particular value of it.- The curly braces hold the bodies, and
printis 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:
swift run
ls -aThe 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:
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:
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 runThe 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 isString?, said "optional string": either a string, ornilwhen 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 thenilcase.?? ""is the nil-coalescing operator: use the value on the left if there is one, otherwise the value on the right. After it,answeris a plainStringthat cannot benil.letdeclares a constant, a name whose value never changes. Usevaronly when it must change. Swift works out the type from the value, so you do not writeString.answer.isEmpty ? "friend" : answerpicks"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 asage + 1.name.countcounts characters as a person sees them, andname.utf8.countcounts 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 ifreadLine()gave a string andInt(line)could turn it into a whole number.Int("thirty")isnil, not a crash. Inside that block,lineandageare ordinary non-optional values.elseruns when either step gavenil.
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:
printf 'Fu\xcc\x81nmi\n' | swift runCheck 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:
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.txt2> 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:
cat > oops.swift <<'SWIFT'
let name: String = readLine() ?? "friend"
print("Hello, \(name)!")
SWIFT
swift oops.swift < /dev/nullCheck 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.swiftwhile another file has@main. Keep start-up code insidestatic func main(). - Reaching for
!to silence the optional error. It moves the problem from compile time to a crash at run time. - Running
swift runoutside the package folder, or runningswift hello.swifton a file insideSources/that uses@mainand 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
swiftDocker 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:
cd ~
rm -rf ~/swift-demoTo move to a newer Swift release later, or remove a toolchain, use swiftly:
swiftly update latest
swiftly uninstall 6.4.2To 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 testinside a fresh package and openTests/helloTests/helloTests.swiftto write your first#expectcheck. The Swift book at docs.swift.org covers optionals and strings in depth.
Part of these paths
Related tutorials
- How to Build Your First iOS App with SwiftUIYou will create an iOS app in Xcode 27.1 with SwiftUI and Swift 6.4, build a small task list with a text field, toggles and swipe to delete, see it in the live preview and the simulator, and run it on your own iPhone.
- Hello World in Kotlin: kotlinc, a runnable JAR and null safetyYou will install the Kotlin 2.4 command-line compiler, build Hello World into a self-contained JAR that runs with java -jar, and extend it to read a name safely when no input arrives.
- Hello World in Objective-C with clang on macOS or GNUstep on LinuxYou will compile and run an Objective-C Hello World with GCC and GNUstep on Ubuntu 26.04 (or clang on a Mac), then split a small Greeter class into a header and an implementation and send it your first message.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials