Jesse A. Green / notebook

Live demo: the DocCompiler guide library as a static, read-only snapshot (October 2026). No backend, no accounts, nothing to submit.

Swift Compiler & Toolchain — User Guide

Generated May 2026 from swiftlang/swift at 8104e4c

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

The Swift programming language compiler, standard library, and developer toolchain. Swift is an open-source project by Apple and the Swift community, providing a modern, safe, and performant language for building applications across macOS, Linux, Windows, iOS, tvOS, watchOS, Android, WebAssembly, and OpenBSD.

This guide covers the Swift compiler (swift/swiftc), the interactive REPL, standalone tools shipped with the toolchain, the benchmark suite, development utilities, and the build-from-source workflow.


1. Quick Start

Compile and run a single file

# Write a Swift file
echo 'print("Hello, Swift!")' > hello.swift

# Compile to an executable
swiftc hello.swift -o hello

# Run it
./hello

Run without compiling (scripting mode)

swift hello.swift

Launch the interactive REPL

swift

You get a 1> prompt. Type Swift expressions, see results immediately. Press Ctrl-D to exit.

Compile with optimizations

swiftc -O hello.swift -o hello          # Performance optimization
swiftc -Osize hello.swift -o hello      # Size optimization
swiftc -Onone hello.swift -o hello      # No optimization (debug, default)

Tip

Use swift hello.swift for quick scripting. Use swiftc when you need a compiled binary, want to control optimization, or are building multi-file projects.


2. Installation

Swift ships with Xcode. Install Xcode from the Mac App Store, or install just the command-line tools:

xcode-select --install

Verify the installation:

swift --version
swiftc --version

To use a specific Swift toolchain downloaded from swift.org, set the toolchain path:

export SWIFT_EXEC=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin/swift

Linux

Download official toolchain tarballs from swift.org/download for supported distributions. Extract and add to your PATH:

tar xzf swift-<version>-<platform>.tar.gz
export PATH=/path/to/swift-<version>/usr/bin:$PATH

Verify:

swift --version

Note

On Linux, Swift requires certain system libraries (libcurl, libxml2, libuuid, etc.). Consult the swift.org download page for the complete list of dependencies for your distribution.

Windows

Download the official Windows installer from swift.org/download. The installer sets up the toolchain and required Visual Studio components.

After installation, verify from a Developer Command Prompt:

swift --version
swiftc --version

Setting the SDK root

On platforms where the SDK is not auto-detected, set the SDKROOT environment variable:

export SDKROOT=/path/to/sdk

The compiler uses SDKROOT to locate system headers and libraries for the target platform.


3. Configuration

Environment variables

Variable Purpose
SWIFT_EXEC Path to the Swift driver binary. Overrides the default swift found in PATH.
SDKROOT SDK root path. Used by the compiler to locate platform headers and libraries.
SWIFT_DETERMINISTIC_HASHING Set to 1 to disable randomized hash seeding. Required for reproducible benchmark results.
ANDROID_NDK_HOME Path to the Android NDK. Required when cross-compiling for Android targets.
SWIFT_OLD_BUILDDIR / SWIFT_NEW_BUILDDIR Build directories used by comparison tools (e.g., cmpcodesize) to diff two builds.

Optimization levels

Flag Effect
-Onone No optimization (default). Fastest compile, largest binary, best debug experience.
-O Performance optimization. Enables inlining, specialization, and other aggressive transforms.
-Osize Size optimization. Minimizes binary size at the cost of some runtime performance.

Module and output control

Flag Purpose
-module-name <name> Set the name of the compiled Swift module.
-emit-module Emit a .swiftmodule file alongside the binary.
-emit-library Produce a dynamic library instead of an executable.
-parse-as-library Treat the input as library code (no implicit @main entry point).
-o <path> Specify the output file path.

Target platform

swiftc -target x86_64-apple-macosx12.0 main.swift
swiftc -target aarch64-unknown-linux-gnu main.swift
swiftc -target x86_64-unknown-windows-msvc main.swift

Important

Cross-compilation requires the appropriate SDK and platform libraries to be available. Set SDKROOT to point to the target platform's SDK when cross-compiling.


4. Core Usage

4.1 The Swift driver

The Swift driver is the main entry point for the toolchain. It orchestrates compilation, linking, and other tasks. When you invoke swift or swiftc, you are calling the driver, which dispatches work to the appropriate sub-tools.

The driver handles these job types internally:

Job type What it does
compile Compile Swift source files into object files
interpret Run Swift code directly without producing a binary
backend LLVM backend code generation (IR to machine code)
merge-module Merge partial .swiftmodule files from separate compilation units
modulewrap Wrap Clang module maps for Swift consumption
link Dynamic linking of object files into an executable or library
static-link Static linking
generate-dSYM Generate debug symbol bundles (macOS)
verify-debug-info Verify debug information integrity
generate-pch Generate precompiled headers for bridging headers
verify-module-interface Verify .swiftinterface file correctness
repl Launch the interactive REPL

4.2 Compiling single files

# Compile to executable
swiftc main.swift -o myapp

# Compile to object file only (no link)
swiftc -c main.swift -o main.o

# Emit LLVM IR
swiftc -emit-ir main.swift -o main.ll

# Emit SIL (Swift Intermediate Language)
swiftc -emit-sil main.swift -o main.sil

# Emit assembly
swiftc -S main.swift -o main.s

4.3 Compiling multi-file projects

# Compile multiple files together
swiftc file1.swift file2.swift file3.swift -o myapp

# Whole-module optimization (all files analyzed together)
swiftc -whole-module-optimization file1.swift file2.swift -o myapp

With whole-module optimization, the compiler sees all files at once and can perform cross-file inlining, dead-code elimination, and specialization.

4.4 Working with modules

# Emit a module alongside the binary
swiftc -emit-module -module-name MyLib source1.swift source2.swift -o libMyLib.dylib

# Import a module from a search path
swiftc -I /path/to/modules main.swift -o myapp

# Link against a library
swiftc -L /path/to/libs -lMyLib main.swift -o myapp

4.5 The Swift REPL

swift
Welcome to Swift!
1> let x = 42
x: Int = 42
2> print("The answer is \(x)")
The answer is 42
3> :quit

The REPL supports multi-line expressions, tab completion, and importing modules. Use :quit or Ctrl-D to exit.

4.6 Scripting mode (interpret)

swift script.swift

Swift files can also include a shebang for direct execution:

#!/usr/bin/env swift
print("Running as a script")
chmod +x script.swift
./script.swift

Tip

Scripting mode compiles and runs in one step. It is convenient for small programs and automation, but the compilation cost is paid on every run. For frequently-executed scripts, consider compiling once with swiftc.

4.7 Precompiled bridging headers

When interoperating with Objective-C or C code, a bridging header can be precompiled for faster builds:

# Generate a precompiled header
swiftc -emit-pch bridging-header.h -o bridging-header.pch

# Use the precompiled header during compilation
swiftc -import-objc-header bridging-header.pch main.swift -o myapp

4.8 Module interface verification

.swiftinterface files describe a module's public API in a textual format. Verify them:

swiftc -verify-module-interface MyModule.swiftinterface

This catches interface changes that would break downstream consumers.

On ELF-based platforms (Linux, Android), autolink information must be extracted separately:

swift-autolink-extract main.o -o main.autolink

The driver handles this automatically during normal compilation; manual invocation is only needed for custom build pipelines.


5. Common Tasks

5.1 Swift Package Manager integration

The Swift compiler integrates with Swift Package Manager (SwiftPM). While SwiftPM lives in a separate repository, the swift driver provides the swift package, swift build, swift test, and swift run subcommands:

# Create a new package
swift package init --type executable

# Build
swift build

# Build with optimizations
swift build -c release

# Run
swift run

# Run tests
swift test

5.2 Building Swift from source

Building the Swift compiler from source requires checking out the Swift repository and its dependencies, then using the build-script orchestrator.

Step 1: Clone the repositories

mkdir swift-project && cd swift-project
git clone https://github.com/swiftlang/swift.git

Use update_checkout to fetch all related repositories (LLVM, Clang, etc.):

swift/utils/update_checkout --clone

Step 2: Build

swift/utils/build-script --release-debuginfo

Common build-script configurations:

Configuration Purpose
--release-debuginfo Optimized build with debug info (recommended for development)
--release Fully optimized, no debug info
--debug Unoptimized, full debug info (slow but best for debugging the compiler)

Warning

Building Swift from source requires substantial disk space (50+ GB) and RAM (16+ GB recommended). A full debug build can take over an hour on a modern machine with 8 cores. Ensure your system meets these requirements before starting.

Step 3: Use the built toolchain

After building, the toolchain binaries are in the build directory. Set SWIFT_EXEC to point to your built compiler:

export SWIFT_EXEC=/path/to/swift-project/build/Ninja-RelWithDebInfo/swift-linux-x86_64/bin/swift

5.3 Running the benchmark suite

Swift ships with 180+ benchmarks in the benchmark/ directory, covering standard library performance, string operations, array algorithms, and more.

Build benchmarks with CMake:

cd swift-project
mkdir build-benchmarks && cd build-benchmarks
cmake ../swift/benchmark -G Ninja \
  -DSWIFT_EXEC=/path/to/swiftc \
  -DCMAKE_BUILD_TYPE=Release
ninja

Build benchmarks with SwiftPM:

cd swift/benchmark
swift build -c release

Run benchmarks:

# Set deterministic hashing (required for reproducible results)
export SWIFT_DETERMINISTIC_HASHING=1

# Run all benchmarks
./Benchmark_O

# List available benchmarks
./Benchmark_O --list

# Run specific iterations
./Benchmark_O --num-iters 5

# Run with multiple samples
./Benchmark_O --num-samples 3

# Filter by tags
./Benchmark_O --tags String,Array

# Skip certain tags
./Benchmark_O --skip-tags skip,unstable

Important

Always set SWIFT_DETERMINISTIC_HASHING=1 before running benchmarks. Without it, hash randomization causes non-deterministic iteration orders in Dictionary and Set operations, producing unreliable timing results.

Optimization-level variants:

Binary Optimization
Benchmark_O -O (performance)
Benchmark_Onone -Onone (no optimization)
Benchmark_Osize -Osize (size optimization)

Benchmarks can be single-source (one .swift file) or multi-source (a directory of .swift files compiled together).

5.4 Using GYB (Generate Your Boilerplate)

GYB is a template processor used extensively in the Swift standard library to generate repetitive Swift code from templates.

# Process a GYB template
python3 utils/gyb.py template.swift.gyb -o template.swift

# Define template variables
python3 utils/gyb.py -D 'MaxWidth=64' template.swift.gyb -o template.swift

# Test mode (parse only, check for errors)
python3 utils/gyb.py --test template.swift.gyb

# Dump parsed template structure
python3 utils/gyb.py --dump template.swift.gyb

# Control line directives
python3 utils/gyb.py --line-directive '' template.swift.gyb -o template.swift

GYB templates use %{ ... }% for Python code blocks and ${...} for expression interpolation within Swift source:

// Example GYB template (IntTypes.swift.gyb)
%  for width in [8, 16, 32, 64]:
extension Int${width} {
    var isPositive: Bool { return self > 0 }
}
%  end

5.5 Demangling Swift symbols

Swift uses name mangling for symbols. The swift-demangle tool decodes them:

# Demangle a symbol from the command line
swift-demangle '$s4main5helloyyF'

# Demangle from stdin (pipe nm output, for example)
nm myapp | swift-demangle

This is indispensable when reading crash logs, inspecting binaries with nm, or debugging linker errors.

5.6 Managing Swift libraries in app bundles

swift-stdlib-tool finds and copies Swift runtime libraries into app bundles, with optional code signing:

# Print which Swift libraries an executable needs
swift-stdlib-tool --print --scan-executable MyApp.app/Contents/MacOS/MyApp

# Copy Swift libraries into the bundle
swift-stdlib-tool --copy \
  --scan-executable MyApp.app/Contents/MacOS/MyApp \
  --scan-folder MyApp.app/Contents/Frameworks \
  --platform macosx \
  --source-libraries /path/to/swift/libs \
  --destination MyApp.app/Contents/Frameworks

# Copy and code-sign
swift-stdlib-tool --copy \
  --scan-executable MyApp.app/Contents/MacOS/MyApp \
  --platform macosx \
  --source-libraries /path/to/swift/libs \
  --destination MyApp.app/Contents/Frameworks \
  --sign "Developer ID Application: Your Name" \
  --keychain /path/to/keychain

# Strip bitcode from copied libraries
swift-stdlib-tool --copy \
  --scan-executable MyApp.app/Contents/MacOS/MyApp \
  --platform iphoneos \
  --source-libraries /path/to/swift/libs \
  --destination MyApp.app/Contents/Frameworks \
  --strip-bitcode

# Copy resource libraries
swift-stdlib-tool --copy \
  --scan-executable MyApp.app/Contents/MacOS/MyApp \
  --platform macosx \
  --source-libraries /path/to/swift/libs \
  --destination MyApp.app/Contents/Frameworks \
  --resource-library libswiftRemoteMirror.dylib \
  --resource-destination MyApp.app/Contents/Resources

# Pass additional flags to codesign
swift-stdlib-tool --copy \
  --scan-executable MyApp.app/Contents/MacOS/MyApp \
  --platform macosx \
  --source-libraries /path/to/swift/libs \
  --destination MyApp.app/Contents/Frameworks \
  --sign "Developer ID Application: Your Name" \
  --Xcodesign --timestamp

Note

swift-stdlib-tool is primarily used in build systems and Xcode build phases. If you are using Xcode or SwiftPM, library embedding is handled automatically. Manual use is for custom build pipelines, CI systems, or non-Xcode toolchains.

5.7 Analyzing compilation statistics

process-stats-dir.py processes compiler statistics output directories:

# Merge stats from a compilation
python3 utils/process-stats-dir.py /path/to/stats-dir

# Generate a flamegraph-compatible output
python3 utils/process-stats-dir.py --flamegraph /path/to/stats-dir

This utility supports 30+ flags for filtering, formatting, and submitting results to LNT (LLVM Nightly Test) infrastructure.

5.8 Analyzing binary code size

# Categorize code size by module
python3 utils/analyze_code_size.py -categorize /path/to/binary

# Analyze a specific architecture in a fat binary
python3 utils/analyze_code_size.py -arch arm64 /path/to/binary

# Output as CSV
python3 utils/analyze_code_size.py -csv /path/to/binary

5.9 Comparing code sizes between builds

Set the environment variables pointing to two build directories, then run:

export SWIFT_OLD_BUILDDIR=/path/to/old/build
export SWIFT_NEW_BUILDDIR=/path/to/new/build
python3 utils/cmpcodesize /path/to/old/binary /path/to/new/binary

This helps measure the code-size impact of compiler changes.

5.10 Dumping module APIs

# Dump the API of a Swift module
python3 utils/swift-api-dump.py -m Foundation -s /path/to/sdk

# Quiet mode
python3 utils/swift-api-dump.py -m MyModule -s /path/to/sdk -q

# Verbose output
python3 utils/swift-api-dump.py -m MyModule -s /path/to/sdk -v

# Specify target triple
python3 utils/swift-api-dump.py -m MyModule -s /path/to/sdk -t x86_64-apple-macosx12.0

# Write to output file
python3 utils/swift-api-dump.py -m MyModule -s /path/to/sdk -o api-dump.txt

5.11 Building SDK module interfaces

# Build .swiftinterface files for all SDK modules
python3 utils/swift_build_sdk_interfaces.py \
  -sdk /path/to/sdk \
  -o /path/to/output \
  -j 8 \
  -v

# Specify additional framework search paths
python3 utils/swift_build_sdk_interfaces.py \
  -sdk /path/to/sdk \
  -o /path/to/output \
  -F /path/to/extra/frameworks

5.12 Running Swift benchmarks with resource monitoring

# Monitor memory usage of a benchmark run
python3 utils/rusage.py --mem ./Benchmark_O --num-iters 3

# Monitor wall-clock time
python3 utils/rusage.py --time ./Benchmark_O --num-iters 3

# Enforce resource limits (kill if exceeded)
python3 utils/rusage.py --enforce --mem 4096 ./Benchmark_O
# Clone all related repositories
swift/utils/update_checkout --clone

# Update existing checkouts to matching revisions
swift/utils/update_checkout

# Use a specific scheme (e.g., a release branch)
swift/utils/update_checkout --scheme release/5.10

5.14 Verifying refactoring correctness

# Check that a refactoring action produces compilable code
python3 utils/refactor-check-compiles.py <source-file>

5.15 Runtime inspection

swift-inspect connects to a running Swift process and dumps runtime information:

swift-inspect <pid>

5.16 Reflection metadata

swift-reflection-dump extracts and displays reflection metadata from Swift binaries:

swift-reflection-dump /path/to/binary

5.17 Debug symbol generation and verification

On macOS, generate dSYM bundles for debugging:

swiftc -g main.swift -o myapp
# The driver generates .dSYM automatically with -g on macOS

# Verify debug info integrity
swiftc -verify-debug-info myapp.dSYM

5.18 Cross-compilation for Android

export ANDROID_NDK_HOME=/path/to/android-ndk

swiftc -target aarch64-unknown-linux-android24 \
  -sdk $ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/sysroot \
  main.swift -o myapp

Caution

Cross-compilation for Android requires a properly configured Android NDK and Swift stdlib built for the Android target. The standard swift.org toolchain downloads do not include Android support by default. You need a custom toolchain build or a community-provided Android SDK.


6. Troubleshooting

6.1 "error: no such module" when importing

Cause: The compiler cannot find the module in its search paths.

Fix: Add the module's location with -I:

swiftc -I /path/to/module/dir main.swift -o myapp

If the module is in a framework bundle:

swiftc -F /path/to/frameworks main.swift -o myapp

6.2 "error: unable to load standard library" on Linux

Cause: The Swift standard library is not in the expected location relative to the compiler binary.

Fix: Ensure the toolchain is properly extracted and PATH includes the usr/bin directory (not a symlink to just the binary). The compiler locates the stdlib relative to its own path.


Cause: Linker cannot find a referenced library or symbol.

Fix:

  • Add library search paths with -L /path/to/lib
  • Link specific libraries with -l<name>
  • Check that the library architecture matches the target
swiftc -L /usr/local/lib -lmylibrary main.swift -o myapp

6.4 Compile times are extremely slow

Possible causes and fixes:

  • Large expressions: The type checker can spend exponential time on complex expressions. Break them into smaller sub-expressions with explicit type annotations.
  • Whole-module mode on debug builds: Use -whole-module-optimization only for release builds.
  • Too many files in one module: Split into multiple modules with clear boundaries.

6.5 "error: expression was too complex to be solved in reasonable time"

Cause: The Swift type checker could not resolve types within the complexity budget.

Fix: Add explicit type annotations to sub-expressions:

// Before (may time out)
let result = array.map { $0 * 2 + 1 }.filter { $0 > threshold }.reduce(0, +)

// After (guides the type checker)
let mapped: [Int] = array.map { $0 * 2 + 1 }
let filtered: [Int] = mapped.filter { $0 > threshold }
let result: Int = filtered.reduce(0, +)

6.6 REPL does not start / crashes immediately

Cause: Missing LLDB or runtime libraries.

Fix:

  • On macOS: ensure Xcode command-line tools are installed (xcode-select --install)
  • On Linux: ensure libpython, libedit, and LLDB dependencies are installed
  • Verify with swift --version first; if that fails, the installation itself is broken

6.7 "error: unsupported option '-static-stdlib'" on macOS

Cause: Static linking of the Swift stdlib is not supported on Apple platforms.

Fix: On macOS/iOS, the Swift runtime is part of the OS (since macOS 10.14.4 / iOS 12.2). Static stdlib linking is available on Linux.


6.8 "cannot load underlying module for '...'" with Clang modules

Cause: A Clang module map references headers that are missing or have errors.

Fix:

  • Verify the module map's header paths are correct
  • Ensure the C headers compile on their own with clang
  • Check SDKROOT is set correctly

6.9 Symbol demangling produces garbage or no output

Cause: The input is not a valid Swift mangled symbol.

Fix: Swift-mangled symbols start with $s (Swift 5+) or _T (Swift 4 and earlier). Ensure you are passing the full symbol name including the prefix:

swift-demangle '$s4main5helloyyF'

6.10 Benchmarks produce inconsistent results

Cause: Hash randomization, system load, or thermal throttling.

Fix:

  1. Set SWIFT_DETERMINISTIC_HASHING=1
  2. Close background applications
  3. Use --num-samples with a value of 3 or higher to collect multiple samples
  4. Run on a quiet machine with consistent thermal conditions

6.11 "error: could not find or use auto-linked library"

Cause: On ELF platforms, the autolink information references a library not in the search path.

Fix: Add the library path with -L or install the missing library. Check which libraries are auto-linked:

swift-autolink-extract mymodule.o

6.12 GYB template produces syntax errors

Cause: Python code in %{ }% blocks has indentation errors or the template mixes tabs and spaces.

Fix:

  • Use consistent indentation in Python blocks
  • Test the template with --test mode before generating:
python3 utils/gyb.py --test template.swift.gyb
  • Use --dump to inspect the parsed template structure:
python3 utils/gyb.py --dump template.swift.gyb

6.13 Build-from-source fails during LLVM compilation

Cause: LLVM is co-built with Swift and requires substantial resources.

Fix:

  • Ensure at least 16 GB of RAM (32 GB recommended for debug builds)
  • Use --release-debuginfo instead of --debug to reduce memory usage
  • Reduce parallelism: build-script uses all available cores by default, which can exhaust RAM on machines with many cores but limited memory

6.14 "error: invalid version" or SDK version mismatch

Cause: The -target triple specifies an OS version not available in the current SDK.

Fix: Check available SDKs with xcrun --show-sdk-path (macOS) and use a matching deployment target:

# Show SDK version
xcrun --show-sdk-version

# Use a compatible target
swiftc -target arm64-apple-macosx13.0 main.swift

6.15 Module interface verification fails

Cause: The .swiftinterface file is out of date or was generated with an incompatible compiler version.

Fix: Regenerate the interface with the same compiler version that will consume it:

swiftc -emit-module-interface -module-name MyLib sources.swift

6.16 "error: use of unresolved identifier" after adding a new file

Cause: The new file is not included in the compilation command.

Fix: Ensure all .swift files in the module are passed to swiftc:

swiftc *.swift -o myapp

With Swift Package Manager, new files in the Sources/ directory are discovered automatically.


6.17 "warning: result of call to '...' is unused"

Cause: A function that returns a value is called without using the result.

Fix: Either use the result or silence the warning with @discardableResult on the function declaration, or assign to _:

_ = someFunction()

6.18 update_checkout fails with merge conflicts

Cause: Local changes in dependent repositories conflict with upstream updates.

Fix: Reset the dependent repositories or clone fresh:

swift/utils/update_checkout --clone --reset-to-remote

6.19 Swift compiler crashes (segfault or assertion failure)

Cause: Compiler bug triggered by specific source code patterns.

Fix:

  1. Reduce the source to a minimal reproducing example
  2. Check Swift GitHub Issues for known issues
  3. File a bug report with the minimal reproducer, compiler version (swift --version), and target platform

6.20 Whole-module optimization runs out of memory

Cause: WMO loads the entire module into memory at once, which can exceed available RAM for very large modules.

Fix:

  • Split the module into smaller sub-modules
  • Use incremental compilation (non-WMO) for debug builds
  • Add more RAM or swap

6.21 "error: cannot convert value of type..." across module boundaries

Cause: Two modules define types with the same name, or a type is imported from an unexpected module.

Fix: Qualify the type with the module name:

let value: MyModule.Config = ...

6.22 swift-stdlib-tool --copy fails with code signing error

Cause: The signing identity is not found in the specified keychain, or the keychain is locked.

Fix:

  • Verify the identity exists: security find-identity -v -p codesigning
  • Unlock the keychain if on CI: security unlock-keychain -p <password> <keychain>
  • Use --keychain to specify the correct keychain path

6.23 Compilation succeeds but binary crashes at runtime

Cause: Mismatched Swift runtime version, missing dynamic libraries, or ABI incompatibility.

Fix:

  • Ensure the Swift runtime on the target matches the compiler version used to build
  • On Linux, verify all required .so files are present alongside the binary or in LD_LIBRARY_PATH
  • Use swift-stdlib-tool --print --scan-executable to check required libraries

6.24 "error: PCH was compiled with module cache path..." mismatch

Cause: A precompiled header was generated with a different module cache path than the current compilation.

Fix: Regenerate the PCH with the current module cache path, or delete the module cache:

rm -rf ~/Library/Developer/Xcode/DerivedData/ModuleCache.noindex/

7. FAQ

Q1: What is the difference between swift and swiftc?

swift without arguments launches the REPL. swift file.swift compiles and runs in one step (interpret mode). swiftc always compiles to produce output files (object files, executables, libraries, etc.). Both invoke the same driver; the behavior changes based on the name used to invoke it.


Q2: What platforms does Swift support?

Swift officially supports macOS, Linux (Ubuntu, CentOS, Amazon Linux, Fedora), and Windows. Community and experimental support exists for iOS, tvOS, watchOS, Android, WebAssembly, and OpenBSD. Cross-compilation is supported via the -target flag.


Q3: How do I check which version of Swift I have?

swift --version

Q4: Can I compile Swift code without Xcode on macOS?

Yes. Install just the command-line tools with xcode-select --install, or download a standalone toolchain from swift.org.


Q5: How do I use Swift as a scripting language?

Add a shebang line to your .swift file and make it executable:

#!/usr/bin/env swift
print("Hello from a Swift script!")
chmod +x script.swift
./script.swift

Q6: What is GYB and why does the Swift project use it?

GYB (Generate Your Boilerplate) is a Python-based template processor (utils/gyb.py). The standard library uses it to generate repetitive type-specific code (e.g., implementations for Int8, Int16, Int32, Int64) from a single template. If you are contributing to the standard library, you will encounter .gyb files.


Q7: How do I build the Swift compiler from source?

Clone the Swift repo, run utils/update_checkout --clone to fetch dependencies, then run utils/build-script --release-debuginfo. See Section 5.2 for full details.


Q8: How much disk space does building Swift from source require?

A release-debuginfo build typically requires 50+ GB of disk space. A full debug build can require more. Ensure you have adequate space before starting.


Q9: How do I run the Swift benchmark suite?

Build the benchmarks with CMake or SwiftPM, set SWIFT_DETERMINISTIC_HASHING=1, then run the benchmark binary. See Section 5.3 for full instructions.


Q10: What does swift-demangle do?

It converts Swift's mangled symbol names (e.g., $s4main5helloyyF) back to human-readable form (e.g., main.hello() -> ()). Use it to read crash logs, nm output, or linker diagnostics.


Q11: How do I cross-compile for a different platform?

Use the -target flag with the appropriate triple and set SDKROOT to the target platform's SDK:

swiftc -target aarch64-unknown-linux-gnu -sdk /path/to/linux-sdk main.swift

Q12: What is the difference between -O, -Onone, and -Osize?

-Onone disables optimization (fastest compilation, best debugging). -O enables aggressive performance optimization. -Osize optimizes for minimal binary size. Default is -Onone.


Q13: Can I use Swift Package Manager with a custom-built compiler?

Yes. Set SWIFT_EXEC to point to your custom compiler, then use swift build, swift test, etc. as normal. SwiftPM will use the specified compiler.


Q14: How do I read a Swift crash log?

Pipe the crash log through swift-demangle to decode mangled symbol names:

cat crash.log | swift-demangle

Q15: What is a .swiftinterface file?

A textual description of a module's public API. It allows modules compiled with different compiler versions to interoperate (library evolution). Generate one with -emit-module-interface. Verify one with the driver's verify-module-interface job type.


Q16: How do I profile Swift compilation times?

Use the -stats-output-dir flag to collect compilation statistics:

swiftc -stats-output-dir /tmp/stats main.swift

Then analyze with utils/process-stats-dir.py.


Q17: What is SIL?

SIL (Swift Intermediate Language) is Swift's high-level intermediate representation, used for optimization and analysis between parsing and LLVM IR generation. View it with:

swiftc -emit-sil main.swift

Q18: How do I reduce a compiler bug to a minimal test case?

  1. Start with the file that triggers the crash or error
  2. Remove code that is not related to the failure
  3. Remove imports and dependencies
  4. Inline code from other files if needed
  5. Verify the minimal file still reproduces the issue
  6. Report at github.com/swiftlang/swift/issues with the reduced case, swift --version, and platform details

Q19: How do I statically link the Swift runtime on Linux?

swiftc -static-stdlib main.swift -o myapp

This produces a binary that does not depend on the Swift shared libraries at runtime. Only available on Linux.


Q20: What is swift-plugin-server?

The macro plugin server process. Swift macros (introduced in Swift 5.9) run in a separate sandboxed process for safety. swift-plugin-server hosts the macro implementations. It is invoked automatically by the compiler when compiling code that uses macros; you do not run it manually.


Q21: How do I suppress specific warnings?

Use -suppress-warnings to suppress all warnings, or silence individual warnings at the source level. There is no per-warning-code suppression flag equivalent to GCC's -Wno-<name>.


Q22: Can I emit just the AST or parse tree?

swiftc -dump-ast main.swift
swiftc -dump-parse main.swift

These are useful for understanding how the compiler interprets your code.


Q23: How do I use swift-refactor?

swift-refactor performs automated source transformations:

swift-refactor <refactoring-kind> -source-filename main.swift -pos <line>:<column>

Q24: How do I check compatibility symbols in a binary?

swift-compatibility-symbols /path/to/binary

This reports which Swift compatibility library symbols the binary references, indicating which OS versions it can target.


Q25: Where should I report Swift compiler bugs?

File issues at github.com/swiftlang/swift/issues. Include: minimal reproducing code, output of swift --version, target platform, and the full error or crash output.