Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 146 ยท Platforms and Ecosystem

Swift on Linux and Windows

Learn how Swift runs on Linux and Windows - what is the same, what differs, conditional compilation, the C library, Foundation, static Linux executables and Docker. Includes runnable portability examples.

Swift began life inside Apple, and for years people assumed it only worked on Apple devices. That has not been true since 2015, when the language went open source with Linux support from the start. Today Swift is a genuinely cross-platform language: the same compiler front end, the same standard library, the same concurrency model and the same package manager run on macOS, Linux, Windows and several other systems. Every example in this tutorial that you ran in the browser was compiled by a Linux toolchain, which is a good reminder that you do not need a Mac to learn Swift.

This lesson explains what stays the same across platforms, what changes, and how to write code that works on all of them. The language examples run here (on Linux). Anything about installing toolchains, building on Windows or packaging in containers needs tools this page cannot run, so those parts are read-only examples and are labelled as such. To follow the lesson comfortably you should know how Swift works and have seen Foundation basics.

What stays the same

The great majority of the code you write is platform independent, because it relies only on things that every platform provides:

  • The language and the standard library: types, optionals, generics, protocols, async/await, actors and Sendable checking, Codable, regular expressions, Duration and everything in the collections lessons.
  • Foundation: on Linux and Windows it comes from two open-source packages. swift-foundation holds the modern core (dates, formatting, JSONEncoder, URL, Data), and swift-corelibs-foundation adds the rest (FileManager, Process, URLSession). The same import Foundation line works everywhere.
  • Dispatch, Synchronization and the Testing library: DispatchQueue, Mutex, Atomic and @Test are available on all of them.
  • Swift Package Manager: Package.swift, swift build, swift test and swift run behave the same on every host.

What changes is everything below and beside these layers: which C library is underneath, which system frameworks exist, how files and processes are named, and how you install and ship the result.

What is different

Topic macOS / iOS Linux Windows
C library module Darwin Glibc (or Musl) WinSDK, ucrt
Apple frameworks (SwiftUI, Combine, os, ...) yes no no
Objective-C interop yes no no
Networking in Foundation URLSession in Foundation URLSession in FoundationNetworking URLSession in FoundationNetworking
Path separator / / \ (and / often works)
Line endings in text files \n \n often \r\n
File name case sensitivity usually insensitive sensitive insensitive
Executable / library names tool, .dylib tool, .so tool.exe, .dll
Environment variable names case sensitive case sensitive case insensitive

The most important row is the second one. Frameworks such as SwiftUI, Combine, os.Logger, CoreData and Keychain Services belong to Apple's operating systems. Code that imports them will not compile elsewhere. That is not a limitation of Swift itself; it is the reason Swift packages that want to be portable depend only on the standard library, Foundation and other cross-platform packages.

A good habit is to keep the core logic of an app in a package that imports only portable modules, and the user interface in a thin layer on top. The core can then be tested on Linux in continuous integration and reused in a server or a command-line tool.

Asking the compiler where it is running

When you do need platform-specific code, Swift uses conditional compilation. The compiler tests conditions while building and includes only the matching branch, so the other branches do not even have to compile on this platform. The conditions you will use most are os(...), arch(...), canImport(...), swift(>=...) and compiler(>=...).

Swift Conditional compilation: which platform is this?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first block is the standard way to import the C library portably. Order matters: the branches are tested top to bottom, and on Linux Glibc is found, which is why the output says so. A static executable built for Linux with the musl library takes the Musl branch instead. The second block, FoundationNetworking, is a classic stumbling block: on Linux and Windows, URLSession and URLRequest are not part of Foundation, and you must import FoundationNetworking in the files that use them. Without the #if canImport guard, that import would fail on Apple platforms.

The conditions combine with &&, || and !, and an unwanted configuration can be turned into a compile error with #error:

Swift Refusing an unsupported platform with #error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The build stops at the #error line and shows exactly the text you wrote. Use it when a platform is really unsupported, since a clear message beats a long cascade of unrelated errors. Use #warning("...") when the code works but something needs attention. Do not use #if where a normal if would do: #if removes code from the build, so it can be wrong without ever being compiled on your machine.

Prefer a runtime value over scattered #if

Code filled with #if os(...) blocks is hard to test, because your test machine only exercises one branch. A better pattern is to isolate the single #if in one place that produces a value, and write the platform logic as an ordinary function on that value. Then all branches can run in one test. Here, a function finds the folder for an app's settings, which differs on each system (APPDATA on Windows, ~/Library/Application Support on macOS, the XDG convention on Linux). The environment is passed in as a dictionary instead of being read globally:

Swift One #if, testable logic for every platform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

All five calls run on this Linux machine, including the Windows one, because the logic no longer depends on where the compiler runs. In real code you would call configDirectory(app: "notes", platform: .current, environment: ProcessInfo.processInfo.environment). This design also gives you a free test suite: each branch and the missing-variable case are plain function calls with plain dictionaries.

Windows details that bite

Two differences are responsible for most "works on my machine" reports between Linux and Windows.

Line endings. Text files created on Windows often end lines with the two-character sequence \r\n. Swift's Character follows Unicode, and Unicode defines that pair as a single grapheme cluster. Splitting a string on the character "\n" therefore finds nothing:

Swift Windows line endings are one Character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The text has 18 Unicode scalars but only 16 Character values, because each \r\n pair counts as one Character. That is why splitting on "\n" finds a single piece: no Character in the string is equal to \n. The reliable tools are split(whereSeparator: \.isNewline), which treats every kind of line break as a separator, and normalizing once at the boundary where text enters your program. The last two lines show the path side of the story: appendingPathComponent joined the pieces with / here, and lastPathComponent of a Windows-style string returned the whole string, since on Linux a backslash is an ordinary character. On a real Windows machine the same URL calls understand drive letters and backslashes, which is exactly why you should use them instead of splitting paths yourself.

Paths. Never build paths by concatenating strings with "/" or "\\". Use URL and its appendingPathComponent, or FileManager's directory helpers, and let Foundation choose the separator. Remember too that Windows file systems are case-insensitive, so a Linux test suite that happily creates Data.json and data.json side by side will break there.

Portability checklist for your code

  • Import FoundationNetworking behind #if canImport(FoundationNetworking) wherever you use URLSession.
  • Replace Apple-only helpers: use Int.random(in:) instead of arc4random, Swift Testing or XCTest instead of platform test frameworks, and a logging package (for example swift-log) instead of os.Logger. autoreleasepool and anything Objective-C related is unavailable.
  • Do not assume DispatchQueue.main runs: in a command-line tool nothing drains the main queue unless you run a main loop. Prefer structured concurrency.
  • Keep file names case-consistent and avoid characters Windows does not allow in names, such as : and ?.
  • Treat ProcessInfo.processInfo.environment keys as case sensitive on Unix and case insensitive on Windows.
  • Test on the platforms you ship to. Continuous integration with a Linux job is the cheapest way to catch Apple-only API use.

Installing the toolchain

This section is a read-only example, because installers and shells cannot run in the browser. Check swift.org/install for the current instructions, since commands change between releases.

On Linux, the recommended installer is swiftly, a version manager that downloads official toolchains and lets you switch between them:

Terminal
# Read-only example: install and use the latest stable toolchain on Linux
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz
tar zxf swiftly-$(uname -m).tar.gz
./swiftly init
swiftly install latest
swift --version

Official toolchains exist for several distributions (Ubuntu, Debian, Fedora, Amazon Linux and Red Hat compatible systems), and the compiler needs a few system packages such as clang, libcurl and libxml2 headers to link Foundation. On Windows, the official toolchain installs through winget or an installer, and it needs the Windows SDK and the C++ build tools from Visual Studio, because Swift links against the same system libraries as C++ programs:

Terminal
# Read-only example: Windows installation from PowerShell or Command Prompt
winget install --id Swift.Toolchain -e

After either installation the workflow is identical: swift package init --type executable, swift build, swift run, swift test.

Static executables and containers

A Swift program on Linux normally links dynamically against the Swift runtime and the system C library, so the target machine needs the Swift runtime libraries or the same libc version. Two features remove that burden. This section is also read-only, since it uses build tools and Docker.

The Static Linux SDK (from swift.org) lets you cross-compile a fully static executable that uses the musl C library and has no external dependencies at all. You install the SDK once and then choose it when building:

Terminal
# Read-only example: build one static binary, even from macOS
swift sdk list
swift build -c release --swift-sdk x86_64-swift-linux-musl

The result runs on any 64-bit Linux, including a minimal scratch container or an Alpine image. The price is a larger binary and a few libraries (those that need dlopen) that cannot be linked statically.

For Docker, the usual recipe is a multi-stage build: compile in the full Swift image, copy the binary into a small runtime image.

DOCKERFILE
# Read-only example: Dockerfile for a Swift server or tool
FROM swift:6.3 AS build
WORKDIR /app
COPY . .
RUN swift build -c release --static-swift-stdlib

FROM ubuntu:24.04
COPY --from=build /app/.build/release/MyTool /usr/local/bin/MyTool
ENTRYPOINT ["MyTool"]

The --static-swift-stdlib flag links the Swift runtime into the executable so that the second stage does not need Swift installed. The final image then holds just the operating system and your binary, usually tens of megabytes instead of more than a gigabyte.

Version numbers in install commands and image tags change with every release. Always check the current Swift release notes and image tags before copying a command into a build pipeline.

Where Swift on Linux and Windows is used

  • Servers and cloud functions: HTTP APIs with Vapor or Hummingbird, usually deployed in containers (see Swift on the server).
  • Command-line tools and build tooling: Swift is a pleasant language for tools that must be fast and typed. Many Apple developer tools are themselves written in Swift and run on Linux in CI.
  • Shared libraries: business logic written once and used by an iOS app, a backend and a Windows tool.
  • Windows apps: command-line tools, libraries and, through community and Microsoft-maintained bindings, native user interfaces. Check the current state of the ecosystem before choosing it for a UI product.
  • Education and CI: exactly what this website does, compiling Swift on Linux for everyone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On Linux, which module do you import to use URLSession?

    On Linux and Windows, URLSession and URLRequest live in FoundationNetworking, so the import is needed in addition to Foundation.
  2. 2. What does #if canImport(Glibc) test?

    canImport checks module availability at compile time. It is the portable way to choose between Darwin, Glibc, Musl and WinSDK.
  3. 3. Why does "a\r\nb".split(separator: "\n") give one piece?

    Unicode treats carriage return plus line feed as one grapheme cluster. Use split(whereSeparator: \.isNewline) or normalize the text first.
  4. 4. Why is a runtime Platform value with one #if better than many #if os() blocks?

    Conditional compilation removes inactive branches from the build, so they are never tested on your machine. Ordinary functions on a value stay compiled and testable.
  5. 5. What does the Static Linux SDK let you build?

    The Static Linux SDK links the Swift runtime and the musl C library into the binary, so it runs on almost any 64-bit Linux.

Summary

  • Swift is a cross-platform language: the language, standard library, concurrency, Foundation core, Dispatch, Synchronization, Testing and SwiftPM work on macOS, Linux and Windows.
  • Apple frameworks (SwiftUI, Combine, os.Logger, Objective-C interop) are not available elsewhere; keep core logic in portable packages.
  • Use #if os(), canImport(), arch(), swift() and compiler() for conditional compilation, #error for unsupported setups, and import Glibc, Musl, Darwin or WinSDK behind canImport.
  • On Linux and Windows import FoundationNetworking for URLSession.
  • Isolate platform differences in one runtime value and testable functions, and avoid hand-built paths and "\n"-only splitting of text that may contain \r\n.
  • Install with swiftly on Linux or winget on Windows, ship static executables with the Static Linux SDK, and package with multi-stage Docker builds.

Next: Embedded Swift