# Swift on Linux: Install with swiftly, Build Packages, and Fix Errors

## Pro Summary

Swift for Linux ships as toolchains built per distribution release. swift.org now recommends the `swiftly` installer, which manages system dependencies and side-by-side versions, or the official `swift` Docker images instead of hand-extracted tarballs. Foundation on Linux is swift-corelibs-foundation layered on swift-foundation: `URLSession` lives in `FoundationNetworking`, XML APIs in `FoundationXML`, and you can import `FoundationEssentials` on its own to avoid the ICU payload. For portable binaries, either link the Swift runtime statically against glibc (`--static-swift-stdlib`) or cross-compile fully static musl binaries with the Static Linux SDK.

```
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
swiftly install --use 6.4
swift build -c release --static-swift-stdlib
swift build --swift-sdk x86_64-swift-linux-musl   # Static Linux SDK
```

Requires: swift-docker publishes Swift 6.4 images for Ubuntu 22.04/24.04/26.04, Debian, Fedora, Amazon Linux and RHEL UBI. The Static Linux SDK must exactly match the installed swift.org toolchain version.

Gotchas:

- Dependency package names change between distro releases: the official Ubuntu 22.04 list uses `libgcc-11-dev`/`libstdc++-11-dev` plus `python3-lldb-13`, 24.04 uses the `-13-` variants, and the `-9-` names belong to Ubuntu 20.04, so copy the list from the matching swift-docker Dockerfile.
- Code that uses `URLSession` compiles on macOS and then fails on Linux with "cannot find 'URLSession' in scope" unless it adds `#if canImport(FoundationNetworking)` / `import FoundationNetworking` / `#endif`.
- The Static Linux SDK cannot be used with Xcode's toolchain on macOS and must match the swift.org toolchain version exactly, so after upgrading run `swift sdk list` and `swift sdk remove` on the old bundle before installing the new one.
- Linux has no Objective-C runtime, so code that relies on `@objc`, `#selector`, `NSObject` KVO or `dynamic` must stay behind `#if canImport(ObjectiveC)`.
- Debug builds are significantly slower than release builds, so build production binaries with `swift build -c release` and find them with `swift build --show-bin-path -c release` instead of hard-coding `.build/` paths.

Primary sources:

- [Install Swift on Linux (swift.org)](https://www.swift.org/install/linux/)
- [Getting Started with the Static Linux SDK (swift.org)](https://www.swift.org/documentation/articles/static-linux-getting-started.html)
- [swift-corelibs-foundation (Foundation modules on non-Darwin platforms)](https://github.com/swiftlang/swift-corelibs-foundation)
- [Building Swift server applications (swift.org)](https://www.swift.org/documentation/server/guides/building.html)

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

To use Swift on Linux, install it with swiftly, the toolchain installer that swift.org recommends, or run one of the official `swift` Docker images. Either way you get the same compiler, Swift Package Manager, Foundation, Swift Testing and the LLDB debugger as on a Mac. What you do not get is Apple's app frameworks such as SwiftUI and UIKit, so Linux is the place for command-line tools, servers and packages, not iPhone apps. This guide covers what to check before installing, the three ways to install, how to verify the toolchain, a first package, how Foundation differs on Linux, server-side Swift, the errors people hit most, and how to switch versions.

> **Difficulty:** Beginner
>
> **Helpful to know first:** basic terminal commands such as `cd` and `ls`, how to install packages with your distribution's package manager, and what a Swift package is.

## Before You Install Swift on Linux

swift.org builds each Swift toolchain for a list of specific distributions and releases, such as Ubuntu LTS releases, Debian, Fedora, Amazon Linux and Red Hat UBI, on both x86_64 and ARM64 (aarch64). A toolchain built for one release, for example Ubuntu 22.04, is not guaranteed to run on another, so start by finding out exactly what you have:

```bash
cat /etc/os-release
uname -m
```

The first command prints your distribution name and version (look at `PRETTY_NAME`); the second prints the CPU architecture, `x86_64` or `aarch64`. Compare both with the platform list on the swift.org install page.

- **Permissions:** you need `sudo` to install the system libraries the toolchain depends on. The toolchain itself installs into your home folder with swiftly.
- **Disk space:** leave a few gigabytes free for the toolchain and for the `.build` folders your packages create.
- **Old installs:** if you once unpacked Swift by hand, remove its line from `~/.bashrc` or `~/.zshrc` first, so two different `swift` commands do not fight over your `PATH`.
- **Windows users:** Swift also runs inside Ubuntu on WSL 2, where every step below works as on a normal Ubuntu machine.

If you develop on a Mac, you do not need any of this there: see [installing Xcode and the Swift tools on macOS](/articles/swift/swift-installing-tools).

## Installing Swift on Linux: Three Ways

### With swiftly (recommended)

swiftly is the official toolchain manager from the Swift project. It downloads the right toolchain for your distribution, keeps several versions side by side, and puts the active one on your `PATH`.

1. Download swiftly for your CPU and unpack it: 

@@BLOCK1@@
2. Run its setup. It installs the latest Swift release and adds swiftly to your shell profile. The flag skips the reminder to reload your shell, because the next step does that: 

@@BLOCK2@@
3. Load swiftly into the current terminal (new terminals load it automatically): 

@@BLOCK3@@
4. If swiftly reports missing system packages, run the install command it prints. It needs `sudo`, and the package names depend on your distribution release, which is why swiftly works them out for you.

### With an official Docker image

If Docker is installed, you can skip installing Swift on the machine altogether. The official images on Docker Hub are named `swift` and are tagged by Swift version:

```bash
docker run --rm swift:6.4 swift --version
docker run --rm -v "$PWD":/work -w /work swift:6.4 swift build
```

The second command mounts the current folder into the container and builds the package in it. Images are also published for several distributions, and the `-slim` variants contain only the runtime libraries, which makes them the image to run a finished program in, not to compile one. Docker is also the easiest way for a Mac user to check that a package builds on Linux.

### From a toolchain archive

For a machine without internet access, or a CI image you build yourself, you can install an archive by hand:

1. Install the system packages that swift.org lists for your exact distribution release. The list changes between releases, so copy it from the install page instead of from an old tutorial.
2. Download the `.tar.gz` for your distribution, release and CPU from swift.org, and its `.sig` file. Import the Swift signing keys listed on swift.org and check the archive with `gpg --verify`.
3. Unpack it into a versioned folder and add its `usr/bin` folder to your `PATH`: 

@@BLOCK5@@

The file name above is the Swift 6.4 archive for Ubuntu 24.04 on x86_64; use the name of the file you downloaded. The folder name carries the version on purpose, so a later version can sit next to it.

## Checking That Swift Works

Ask the compiler for its version first:

```bash
swift --version
# Swift version 6.4 (swift-6.4-RELEASE)
# Target: x86_64-unknown-linux-gnu
```

The target line ends in `linux-gnu`, with `aarch64` instead of `x86_64` on ARM machines. With swiftly, `swiftly list` shows every installed toolchain and which one is in use.

A version string only proves the binary starts. Compile and run real code too, once as a script and once as a binary:

```bash
# Run one file directly, then compile it to a binary
echo 'print("Swift works on Linux")' > hello.swift
swift hello.swift
swiftc hello.swift -o hello && ./hello
```

Both commands print `Swift works on Linux`. Finally, check Swift Package Manager and the linker with the package template:

```bash
mkdir hello-pkg && cd hello-pkg
swift package init --type executable
swift run
```

`swift run` builds the package and its last line of output is `Hello, world!`. If all three checks pass, the toolchain, Foundation and the system libraries are in place.

## Building Your First Swift Package on Linux

The template works, but a package you write yourself shows the layout better. Create the folders:

```bash
mkdir -p configcheck/Sources/configcheck
cd configcheck
```

Save this as `Package.swift` in the `configcheck` folder. The first line is required: it sets the minimum tools version, and with 6.0 or later the package also builds in the Swift 6 language mode.

```swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "configcheck",
    targets: [
        .executableTarget(name: "configcheck")
    ]
)
```

Then save the program as `Sources/configcheck/main.swift`. The file must be called `main.swift` because it runs code at the top level. It decodes and encodes JSON with Foundation, which works the same on Linux as on a Mac:

```swift
import Foundation

struct ServerConfig: Codable {
    let host: String
    let port: Int
    let workers: Int
}

let json = #"{"host": "0.0.0.0", "port": 8080, "workers": 4}"#
let config = try JSONDecoder().decode(ServerConfig.self, from: Data(json.utf8))
print("Listening on \(config.host):\(config.port) with \(config.workers) workers")

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
print(String(decoding: try encoder.encode(config), as: UTF8.self))
// Output:
// Listening on 0.0.0.0:8080 with 4 workers
// {"host":"0.0.0.0","port":8080,"workers":4}
```

Output (tested with Swift 6.4):

```text
Listening on 0.0.0.0:8080 with 4 workers
{"host":"0.0.0.0","port":8080,"workers":4}
```

Build and run it from the `configcheck` folder. `swift run` makes a debug build; build with `-c release` before you deploy or measure anything, because debug builds are much slower:

```bash
swift run
swift build -c release
```

To add tests, create `Tests/configcheckTests`, add a `.testTarget` to the manifest, and run `swift test`: Swift Testing and XCTest both work on Linux. Dependencies, products and targets work exactly as on macOS; see [Swift Package Manager](/articles/swift/swift-spm) for the manifest in depth.

For an editor, the official Swift extension for VS Code (and any editor that speaks the Language Server Protocol) uses `sourcekit-lsp`, which ships inside the toolchain. If code completion does not work, run `which sourcekit-lsp` in the terminal and make sure the editor sees the same `PATH`.

## Foundation on Linux: What Is the Same and What Moves

Since Swift 6, Foundation on Linux is built on swift-foundation, the Swift rewrite of Foundation's core that Apple's platforms also use. swift-corelibs-foundation sits on top of it and keeps the older APIs. `import Foundation` gives you `Data`, `Date`, `URL`, `JSONEncoder`, `FileManager`, formatting and the rest, with two differences that break code written on a Mac:

- Networking types (`URLSession`, `URLRequest`, `HTTPURLResponse`) live in a separate module, `FoundationNetworking`.
- XML types such as `XMLParser` live in `FoundationXML`.

On a Mac both are part of Foundation and the extra modules do not exist, so import them only where they can be imported:

```swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

func healthCheckRequest(for host: String) -> URLRequest? {
    guard let url = URL(string: "https://\(host)/health") else { return nil }
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    request.timeoutInterval = 5
    return request
}

if let request = healthCheckRequest(for: "example.com") {
    print(request.httpMethod ?? "", request.url?.absoluteString ?? "")
}
// Output: HEAD https://example.com/health
```

Output (tested with Swift 6.4):

```text
HEAD https://example.com/health
```

The same file builds on macOS and Linux. Without the three `#if` lines it still builds on a Mac but fails on Linux, which is why a package that "works on my machine" should also be built in a Linux container or on Linux CI. The [conditional compilation](/articles/swift/swift-build-config-conditional-compilation) article covers `canImport` and `os()` checks in detail.

For small command-line tools and serverless functions there is a third option: `FoundationEssentials`, the core of swift-foundation without the internationalization data. It has types such as `Data`, `Date`, `URL`, `UUID` and the JSON coders, and leaves out locale-aware formatting, which keeps statically linked programs much smaller. It cannot be imported on its own on Apple platforms, so guard it the same way:

```swift
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif

let payload = Data(#"{"ok":true}"#.utf8)
print(payload.count)   // Output: 11
```

Output (tested with Swift 6.4):

```text
11
```

## What Swift on Linux Does Not Include

The language, the standard library, Swift concurrency, Dispatch, Foundation, Swift Testing and XCTest are all available. Apple's closed-source frameworks are not:

| On a Mac you use | On Linux |
| --- | --- |
| SwiftUI, UIKit, AppKit | Not available. There is no official GUI framework for Linux; Swift there is for tools and servers. |
| Combine | Not available. Use async/await and `AsyncSequence`. |
| `os.Logger` (OSLog) | Not available. Server packages use the swift-log package. |
| Core Data, SwiftData, CloudKit | Not available. Use a database driver package. |
| Objective-C runtime (`@objc`, `#selector`, KVO) | Not available. |
| Xcode | Not available. Use VS Code or another editor with `sourcekit-lsp`, plus the `swift` command line. |

A good structure for shared code is a library target with the logic, built everywhere, plus thin platform-specific targets: an iOS app on Apple platforms and a command-line or server target on Linux.

## Server-Side Swift on Linux

Linux is where most server-side Swift runs. The common building blocks are open-source packages:

- **SwiftNIO**, Apple's event-driven networking library, which most server frameworks are built on.
- **Vapor** and **Hummingbird**, web frameworks for HTTP APIs and websites.
- **AsyncHTTPClient** for HTTP calls, **swift-log** and **swift-metrics** for logging and metrics.
- **Swift AWS Lambda Runtime** for serverless functions.

The Swift Server Workgroup reviews packages like these and lists them on swift.org. A typical deployment builds the release binary in the `swift:6.4` image and copies it into the much smaller `swift:6.4-slim` image, which has the Swift runtime libraries but no compiler. Server code uses async/await heavily; if that is new to you, read [Swift async and await](/articles/swift/swift-async-await).

## Errors When Installing and Building Swift on Linux

### swift: command not found

The shell cannot find the `swift` binary. With swiftly, the current terminal has not loaded swiftly's `env.sh` yet. With an archive install, the toolchain's `usr/bin` folder is not on your `PATH`, or you edited a profile file your shell does not read.

```bash
# swiftly: load it into this terminal, or open a new terminal
. "${SWIFTLY_HOME_DIR:-$HOME/.local/share/swiftly}/env.sh"
hash -r

# archive install: put the toolchain's usr/bin folder on PATH
export PATH=/opt/swift-6.4/usr/bin:$PATH
swift --version
```

### error while loading shared libraries: libswiftCore.so

The full message is `error while loading shared libraries: libswiftCore.so: cannot open shared object file: No such file or directory`. Your program was built against the Swift runtime libraries, and the machine running it does not have them, which happens when you copy a binary to a plain server or a plain `ubuntu` container. Run it where the runtime exists (the `swift:6.4-slim` image), or link the runtime into the binary:

```bash
swift build -c release --static-swift-stdlib
```

The same "error while loading shared libraries" message with a system library name instead means a system package is missing; install the dependency list for your distribution. A message such as `version `GLIBC_2.xx' not found` means the toolchain or binary was built for a newer distribution release than the one you are running.

### cannot find 'URLSession' in scope

Code that compiles on macOS fails on Linux with `cannot find 'URLSession' in scope` (or the same message for `URLRequest`). The networking types are in `FoundationNetworking` on Linux. Add the `#if canImport(FoundationNetworking)` import shown in the Foundation section.

### no such module 'SwiftUI'

The compiler reports `no such module 'SwiftUI'` (or `'UIKit'`, `'AppKit'`, `'Combine'`) because these frameworks only exist on Apple platforms. Move the code that needs them into a target that is only built for Apple platforms, or guard the import with `#if canImport(SwiftUI)`, and keep the shared logic free of them.

### 'main' attribute cannot be used in a module that contains top-level code

A target can have only one entry point. You get this error when it contains a `main.swift` file and also a type marked `@main`, for example after copying a template file into a target that already had `main.swift`. Keep one of them. The opposite mistake, top-level statements in a file that is not called `main.swift`, gives `expressions are not allowed at the top level`.

### Source files for target … should be located under 'Sources/…'

Linux file systems are case-sensitive and macOS's usually are not. In a package with several targets, a folder named `Sources/ConfigCheck` for a target named `configcheck` builds on a Mac, but on Linux SwiftPM does not find it and reports that `Source files for target configcheck should be located under 'Sources/configcheck', or a custom sources path can be set with the 'path' property in Package.swift`. Rename the folder so it matches the target name exactly, letter case included. The same applies to file names you open at run time.

## Updating Swift and Switching Versions

Install new versions next to the old one and switch, so you can go back if a project breaks. swiftly does this for you:

```bash
swiftly install latest
swiftly install 6.3
swiftly list
swiftly use 6.3
swiftly uninstall 6.2
swiftly self-update
```

`install latest` adds the newest release, `install 6.3` adds a specific one, `use` switches the active toolchain, `uninstall` removes one you no longer need, and `self-update` updates swiftly itself. To pin a project to a version, add a `.swift-version` file with the version number (for example `6.4`) to the project root; swiftly picks that toolchain when you work in the project.

With archive installs, unpack the new version into its own folder, such as `/opt/swift-6.5`, test it in one terminal by putting its `usr/bin` first on `PATH`, and only then change your profile. With Docker, change the image tag. Before you move a project to a new major version, read [Swift versions and compatibility](/articles/swift/swift-versions-compatibility).

## Summary

- Install with swiftly (recommended), an official `swift` Docker image, or a signed archive that matches your distribution release and CPU.
- Check with `swift --version`, then compile a file and run `swift run` on a package.
- Foundation works on Linux, but networking needs `FoundationNetworking` and XML needs `FoundationXML`; guard both with `#if canImport`.
- SwiftUI, UIKit, AppKit, Combine and other Apple frameworks are not available: Linux Swift is for tools, packages and servers.
- Most setup errors are a missing `PATH` entry, missing runtime or system libraries, or a case mismatch in folder names.
- Keep versions side by side and switch with `swiftly use`.

Next step: build a small command-line tool with dependencies and tests, following [Swift Package Manager](/articles/swift/swift-spm).

## Where AI Coding Assistants Get This Wrong

- Often suggested: Hard-codes `import Glibc` or `#if os(Linux) import Glibc` for C standard library access.
  Instead: Use a `canImport` chain, with each `import` on its own line: `#if canImport(Darwin)` then `import Darwin`, `#elseif canImport(Glibc)` then `import Glibc`, `#elseif canImport(Musl)` then `import Musl`, `#elseif os(Windows)` then `import ucrt`, `#endif`. Or depend on Foundation alone. (The Static Linux SDK is built on musl rather than glibc, so the `Glibc` module is not available when you build with it.)
- Often suggested: Writes networking code with only `import Foundation` and assumes it builds on Linux because it builds on macOS.
  Instead: Conditionally import `FoundationNetworking` (and `FoundationXML` for `XMLParser`), and run the build in a `swift:<version>` container or on Linux CI. (On non-Darwin platforms swift-corelibs-foundation ships `URLSession` in the separate `FoundationNetworking` module.)
- Often suggested: Gives outdated install steps: download a Swift 5.x tarball, pair it with an apt dependency list from a different Ubuntu release, and edit `PATH` by hand, or use Xcode's toolchain with the Static Linux SDK.
  Instead: Install with swiftly (`swiftly install --use <version>`, `.swift-version` per project) or use the official `swift` Docker images. For static binaries, install the Static Linux SDK that matches your swift.org toolchain with `swift sdk install <url> --checksum <sha>`. (These are the install paths that swift.org currently documents, and its static SDK guide says Xcode's toolchain can't use that SDK.)
