Skip to main content

Programming languages · Intermediate · 25 min

Build a command-line tool in Swift on Linux with Swift Package Manager

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 (swift:6.4 image) · Swift 6.4.3 · swift-argument-parser 1.8.2

You will build wordtally, a Swift 6.4 word-count tool for Linux with options, flags and an async main from swift-argument-parser, a folder search built on Foundation's FileManager, Swift Testing tests and a release binary that runs without a Swift toolchain installed.

On this page

Swift is best known for iPhone and Mac apps, but the compiler, the package manager and the core libraries are open source and run on Linux. A Swift command-line tool compiles to one native binary, starts instantly, and needs no interpreter on the machine that runs it. That makes it a reasonable choice for the small tools a backend or mobile team keeps around: log scanners, release scripts, data checks.

In this tutorial you build wordtally. Give it files or folders, or pipe text into it, and it prints the number of files, lines, words and characters, followed by the most common words. Along the way you use the pieces a real Swift tool needs on Linux:

  • Swift Package Manager (SwiftPM) to create the project, fetch a library and build.
  • swift-argument-parser, the Swift project's library for options, flags, --help and errors.
  • async main and a task group, so several files are read at once.
  • Foundation's FileManager, and the places where Foundation on Linux is not the same as on a Mac.
  • Swift 6 strict concurrency, which refuses to compile a data race.
  • Swift Testing, the test library that ships with Swift 6.
  • A release build that you can copy to another Linux machine.

Everything here was written for Swift 6.4.3 on Ubuntu 26.04. The commands work the same on a Mac with Swift 6.4, apart from the static binary in the last step, which is Linux only.

Step 1 · Create an executable package

SwiftPM fetches libraries with Git, so make sure it is installed:

Bash
sudo apt update
sudo apt install -y git

Create the project in a throwaway folder. --type executable makes a package that builds a program rather than a library, and --name sets the program's name:

Bash
mkdir -p ~/wordtally-demo
cd ~/wordtally-demo
swift package init --type executable --name wordtally
swift run wordtally

swift package init writes three things: Package.swift, the manifest that describes the package; Sources/wordtally/, with a Swift file holding a @main struct that prints a greeting; and Tests/wordtallyTests/, with an empty Swift Testing test. swift run builds the program in debug mode and runs it.

Check it worked

The last line of output is Hello, world!. Above it, SwiftPM reports the build, ending with a line like Build of product 'wordtally' complete!. The program itself is in .build/debug/wordtally.

Step 2 · Add swift-argument-parser and split the package into targets

You will put the counting code in a library target, WordTallyCore, and keep the executable thin. The tests then import the library directly, and the same code could later sit behind a web service or an iOS app.

This deletes the generated greeting and its empty test, so you can lay out the folders for the new targets:

Bash
cd ~/wordtally-demo
rm Sources/wordtally/*.swift
rm -r Tests/wordtallyTests
mkdir -p Sources/WordTallyCore Tests/WordTallyCoreTests

Replace Package.swift with this manifest:

Bash
cat > Package.swift <<'SWIFT'
// swift-tools-version: 6.4
import PackageDescription

let package = Package(
    name: "wordtally",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.8.2"),
    ],
    targets: [
        .target(
            name: "WordTallyCore",
            swiftSettings: [.enableUpcomingFeature("ApproachableConcurrency")]
        ),
        .executableTarget(
            name: "wordtally",
            dependencies: [
                "WordTallyCore",
                .product(name: "ArgumentParser", package: "swift-argument-parser"),
            ],
            swiftSettings: [.enableUpcomingFeature("ApproachableConcurrency")]
        ),
        .testTarget(
            name: "WordTallyCoreTests",
            dependencies: ["WordTallyCore"],
            swiftSettings: [.enableUpcomingFeature("ApproachableConcurrency")]
        ),
    ]
)
SWIFT
swift package resolve

What each part does:

  • // swift-tools-version: 6.4 is not a comment to SwiftPM. It sets the oldest Swift that can build the package, and with a 6.x version the code compiles in the Swift 6 language mode, where data-race checks are errors rather than warnings.
  • from: "1.8.2" accepts 1.8.2 or any later 1.x release. swift package resolve downloads the library and records the exact version in Package.resolved; commit that file so everyone builds the same version.
  • .product(name: "ArgumentParser", ...) is the module you will import. The package name and the module name are different, which trips people up.
  • ApproachableConcurrency is what swift package init turns on for new packages in Swift 6.4: a bundle of upcoming concurrency features that make async code behave more predictably. Keep it.
  • platforms: [.macOS(.v13)] has no effect on Linux. On a Mac, SwiftPM otherwise assumes an old macOS release, and Foundation APIs such as URL(filePath:) that you use below fail to compile there with "only available in macOS 13.0 or newer". On Linux, Foundation ships with the toolchain, so there is no OS version to target.

If you pay for mobile data by the megabyte, the first resolve is the expensive part: it clones the swift-argument-parser repository from GitHub. Later builds reuse the copy in .build/checkouts, so run it once on Wi-Fi and you can keep working offline.

Check it worked

swift package resolve ends without an error and Package.resolved names swift-argument-parser with a 1.8 version. Run grep -A3 argument-parser Package.resolved to see it. SwiftPM may also print two warnings that the wordtally and WordTallyCoreTests targets have no source files under Sources/wordtally and Tests/WordTallyCoreTests. Both are expected: the folders are empty for now, and you fill them in later steps.

Step 3 · Write the counting code and the file finder

The library has two files. The first counts text. Create Sources/WordTallyCore/Tally.swift:

Bash
cd ~/wordtally-demo
cat > Sources/WordTallyCore/Tally.swift <<'SWIFT'
import Foundation

/// Settings that change what counts as a word.
public struct TallyOptions: Sendable {
    public var minLength: Int
    public var caseSensitive: Bool

    public init(minLength: Int = 1, caseSensitive: Bool = false) {
        self.minLength = minLength
        self.caseSensitive = caseSensitive
    }
}

/// Counts for one piece of text, or the sum of several.
public struct Tally: Sendable, Equatable {
    public var files = 0
    public var lines = 0
    public var words = 0
    public var characters = 0
    public var counts: [String: Int] = [:]

    public init() {}

    /// Counts the lines, words and characters in `text`.
    public static func of(_ text: String, options: TallyOptions = TallyOptions()) -> Tally {
        var tally = Tally()
        tally.characters = text.count
        tally.lines = text.unicodeScalars.filter { $0 == "\n" }.count
        let pieces = text.split { !$0.isLetter && !$0.isNumber && $0 != "'" }
        for piece in pieces {
            let word = piece.trimmingCharacters(in: CharacterSet(charactersIn: "'"))
            guard !word.isEmpty else { continue }
            tally.words += 1
            guard word.count >= options.minLength else { continue }
            let key = options.caseSensitive ? word : word.lowercased()
            tally.counts[key, default: 0] += 1
        }
        return tally
    }

    /// Reads a file as UTF-8 and counts it.
    public static func read(file path: String, options: TallyOptions = TallyOptions()) throws -> Tally {
        let data: Data
        do {
            data = try Data(contentsOf: URL(filePath: path))
        } catch {
            throw TallyError.unreadable(path)
        }
        var tally = Tally.of(String(decoding: data, as: UTF8.self), options: options)
        tally.files = 1
        return tally
    }

    /// The `n` most common words, most frequent first, ties in alphabetical order.
    public func top(_ n: Int) -> [(word: String, count: Int)] {
        counts
            .sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
            .prefix(n)
            .map { (word: $0.key, count: $0.value) }
    }

    /// Adds another tally to this one.
    public mutating func add(_ other: Tally) {
        files += other.files
        lines += other.lines
        words += other.words
        characters += other.characters
        counts.merge(other.counts, uniquingKeysWith: +)
    }
}

public enum TallyError: Error, Equatable, CustomStringConvertible {
    case notFound(String)
    case unreadable(String)

    public var description: String {
        switch self {
        case .notFound(let path): "no such file or folder: \(path)"
        case .unreadable(let path): "cannot read \(path)"
        }
    }
}
SWIFT

Two details about Swift strings matter here:

  • A Swift Character is what a reader sees as one character, even when it is made of several Unicode code points. Yorùbá ẹ̀ is three code points (e, a dot below, a grave accent) but one Character, so text.count does not over-count tone-marked or accented text, and isLetter keeps ẹ̀kọ́ as one word. That matters for tools that handle Yorùbá, Igbo, Vietnamese or French.
  • The Windows line ending \r\n is also a single Character, and it is not equal to "\n". Counting Characters equal to "\n" would miss every line in a file saved on Windows. Counting the \n code points in unicodeScalars works for both.

String(decoding:as:) never fails: bytes that are not valid UTF-8 become the replacement character �, so one badly encoded file does not stop the whole run.

The second file turns what the user typed into a list of files, searching folders with FileManager. Create Sources/WordTallyCore/TextFiles.swift:

Bash
cat > Sources/WordTallyCore/TextFiles.swift <<'SWIFT'
import Foundation

public enum TextFiles {
    /// Turns the paths the user typed into a list of files.
    /// A folder is searched, including its subfolders, for files whose
    /// extension is in `extensions` (compared in lower case).
    public static func expand(_ paths: [String], extensions: Set<String>) throws -> [String] {
        let fileManager = FileManager.default
        var files: [String] = []
        for path in paths {
            var isFolder: ObjCBool = false
            guard fileManager.fileExists(atPath: path, isDirectory: &isFolder) else {
                throw TallyError.notFound(path)
            }
            guard isFolder.boolValue else {
                files.append(path)
                continue
            }
            guard let walker = fileManager.enumerator(atPath: path) else {
                throw TallyError.unreadable(path)
            }
            var found: [String] = []
            for case let relative as String in walker {
                let url = URL(filePath: path).appending(path: relative)
                guard extensions.contains(url.pathExtension.lowercased()) else { continue }
                found.append(url.path(percentEncoded: false))
            }
            files += found.sorted()
        }
        return files
    }
}
SWIFT
swift build

Foundation on Linux is not the macOS framework

On a Mac, Foundation is part of the operating system. On Linux it ships inside the Swift toolchain and is built from two open-source projects: swift-foundation, which provides the modern core (URL, Data, FileManager, JSON coding, dates), and swift-corelibs-foundation, which supplies the older class-based API on top. The code above compiles unchanged on both, but there are differences worth knowing:

  • There is no Objective-C runtime on Linux. ObjCBool in fileExists(atPath:isDirectory:) is a plain struct that Foundation provides so the same call compiles everywhere. Code that uses @objc, NSObject subclassing tricks or key-value observing is where ports from macOS usually break.
  • Standard folders follow the Linux (XDG) conventions. FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) gives ~/.cache (or $XDG_CACHE_HOME) on Linux and ~/Library/Caches on a Mac. Never hard-code ~/Library in a tool that should run on both.
  • Linux file systems are case-sensitive and the default macOS one is not. Notes.TXT and notes.txt are two files on Ubuntu. That is why expand lower-cases the extension before comparing it.
  • If your binary size matters, import FoundationEssentials instead of import Foundation gives you URL, Data and FileManager without the large internationalisation data. You lose locale-aware formatting. This tutorial keeps the full Foundation for simplicity.

Check it worked

swift build ends with Build complete! and no errors. Two warnings are expected, one saying source files for target wordtally should be located under Sources/wordtally and the matching one for WordTallyCoreTests. The wordtally target gets its source in the next step and the test target in the testing step.

Step 4 · Write the command with options, flags and an async main

Now the program itself. Create Sources/wordtally/WordTally.swift:

Bash
cd ~/wordtally-demo
cat > Sources/wordtally/WordTally.swift <<'SWIFT'
import ArgumentParser
import Foundation
import WordTallyCore

@main
struct WordTally: AsyncParsableCommand {
    static let configuration = CommandConfiguration(
        commandName: "wordtally",
        abstract: "Count lines, words and characters, and list the most common words.",
        version: "0.1.0"
    )

    @Argument(help: "Files or folders to read. Reads standard input when you give none.")
    var paths: [String] = []

    @Option(name: [.short, .long], help: "How many of the most common words to list.")
    var top = 5

    @Option(help: "Leave words shorter than this out of the top list.")
    var minLength = 1

    @Option(name: .customLong("ext"), help: "File extensions to read inside folders. Repeat for more than one.")
    var extensions = ["txt", "md"]

    @Flag(name: [.short, .long], help: "Count Word and word as different words.")
    var caseSensitive = false

    @Flag(name: [.short, .long], help: "Print the totals only.")
    var quiet = false

    mutating func validate() throws {
        guard top >= 0 else { throw ValidationError("--top must be 0 or more.") }
        guard minLength >= 1 else { throw ValidationError("--min-length must be 1 or more.") }
    }

    mutating func run() async throws {
        let options = TallyOptions(minLength: minLength, caseSensitive: caseSensitive)
        var total = Tally()

        if paths.isEmpty {
            let data = try FileHandle.standardInput.readToEnd() ?? Data()
            total = Tally.of(String(decoding: data, as: UTF8.self), options: options)
        } else {
            let files = try TextFiles.expand(paths, extensions: Set(extensions.map { $0.lowercased() }))
            total = try await withThrowingTaskGroup(of: Tally.self) { group in
                for file in files {
                    group.addTask { try Tally.read(file: file, options: options) }
                }
                var sum = Tally()
                for try await part in group {
                    sum.add(part)
                }
                return sum
            }
        }

        print("files: \(total.files)  lines: \(total.lines)  words: \(total.words)  characters: \(total.characters)")
        guard !quiet else { return }
        for (word, count) in total.top(top) {
            print("\(String(count).leftPadded(to: 6))  \(word)")
        }
    }
}

extension String {
    func leftPadded(to width: Int) -> String {
        String(repeating: " ", count: max(0, width - count)) + self
    }
}
SWIFT

How swift-argument-parser reads this struct:

  • @Argument is a positional value. Because paths is an array, the user can give any number of them.
  • @Option takes a value (--top 3). The property name becomes the long name in kebab case, so minLength is --min-length. .short adds -t, and .customLong("ext") picks a name that differs from the property.
  • @Flag is a Boolean switch with no value (--quiet, -q).
  • The default value of each property is the default the user sees in --help. The doc string after help: is the description.
  • validate() runs after parsing and before run(). A ValidationError there prints your message with the usage line and exits with code 64, the conventional "usage error" code.
  • Any other error thrown from run() prints Error: followed by the error's description, and exits with code 1.
  • AsyncParsableCommand with @main gives you an async entry point, so run() can await. The task group reads each file in its own child task, at the same time, and adds up the results as they arrive.

configuration is declared with static let. Older examples often write static var configuration, which Swift 6 rejects: a static var is shared mutable state, the same problem you will see in the next step.

Make a few sample files to count:

Bash
mkdir -p samples/more
cat > samples/poem.txt <<'TXT'
The rain falls on the roof.
The roof holds; the rain runs off.
TXT
cat > samples/more/notes.md <<'TXT'
Rain today. Ẹ̀kọ́ dára, ẹ̀kọ́ dára.
TXT
printf 'id,word\n1,ignored\n' > samples/more/words.csv

Check it worked

Build and run the tool on the folder, ask for its help, and pipe text into it:

Bash
swift run wordtally samples --top 3
swift run wordtally --help
printf 'one two two\nthree\n' | swift run wordtally

The first run prints files: 2 lines: 3 words: 19 characters: 95, then 4 the, 3 rain and 2 dára. It read the .txt and .md files, including the one in the subfolder, and skipped the .csv. --help lists every argument, option and flag with its default. The piped run reports files: 0 because it read standard input, and lists two first.

Now try two mistakes. Each prints an error, and echo $? shows the exit code:

Bash
swift run wordtally no-such-folder; echo "exit code: $?"
swift run wordtally --min-length 0; echo "exit code: $?"

The first prints Error: no such file or folder: no-such-folder and exit code 1. The second prints Error: --min-length must be 1 or more. with the usage line, and exit code 64. A shell script that calls wordtally can tell the two kinds of failure apart.

Step 5 · Let Swift 6 catch a shared mutable global

Suppose you want to count files as the tasks read them, and reach for the quickest fix: a global variable. Add this file:

Bash
cd ~/wordtally-demo
cat > Sources/wordtally/Progress.swift <<'SWIFT'
import WordTallyCore

// Keeps a running count of files read, shared by every task.
var filesRead = 0

func readAndCount(_ file: String, options: TallyOptions) throws -> Tally {
    filesRead += 1
    return try Tally.read(file: file, options: options)
}
SWIFT

Build it:

Bash
swift build

The build fails with an error like this:

Text
error: var 'filesRead' is not concurrency-safe because it is nonisolated global shared mutable state
note: convert 'filesRead' to a 'let' constant to make 'Sendable' shared state immutable
note: add '@MainActor' to make var 'filesRead' part of global actor 'MainActor'
note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism

The compiler is right. If readAndCount were called from the task group, several child tasks would run filesRead += 1 at the same moment on different threads. That is a data race: increments get lost, and the count comes out wrong on some runs and right on others, which is the worst kind of bug to track down. In the Swift 6 language mode this is a compile error, not a warning, and it is reported for the declaration whether or not anything calls it yet.

The notes list the ways out:

  • Make it a let, if the value never changes after start-up. A constant of a Sendable type is safe to share.
  • Put it on an actor, such as @MainActor. Every access then goes through that actor one at a time, and callers in other tasks must await it.
  • Protect it with a lock, such as Mutex from the Synchronization module in the standard library.
  • nonisolated(unsafe) var tells the compiler to stop checking. It does not make the code safe, so use it only when something the compiler cannot see already protects the value.

The best fix here is to not share the counter at all. Each child task already returns a Tally whose files is 1, and the task group adds them up in one place. Delete the file:

Bash
rm Sources/wordtally/Progress.swift
swift build

Check it worked

swift build succeeds again and swift run wordtally samples -q still prints files: 2. The count comes from values the tasks return, not from a variable they all write to.

Step 6 · Test the library with Swift Testing

Swift Testing comes with the Swift 6 toolchain on Linux and macOS, so there is nothing to add to Package.swift. A test is a function marked @Test, and #expect checks a condition and, on failure, shows the values on each side. Create Tests/WordTallyCoreTests/WordTallyCoreTests.swift:

Bash
cd ~/wordtally-demo
cat > Tests/WordTallyCoreTests/WordTallyCoreTests.swift <<'SWIFT'
import Foundation
import Testing
import WordTallyCore

@Suite struct TallyTests {
    @Test func countsLinesWordsAndCharacters() {
        let tally = Tally.of("one two\nthree\n")
        #expect(tally.lines == 2)
        #expect(tally.words == 3)
        #expect(tally.characters == 14)
    }

    @Test func foldsCaseUnlessAskedNotTo() {
        let text = "Rain rain RAIN"
        #expect(Tally.of(text).counts == ["rain": 3])
        let exact = Tally.of(text, options: TallyOptions(caseSensitive: true))
        #expect(exact.counts.count == 3)
    }

    @Test("Short words stay out of the top list", arguments: [(1, 3), (3, 2), (5, 0)])
    func minimumLength(minLength: Int, expected: Int) {
        let tally = Tally.of("a cat sat", options: TallyOptions(minLength: minLength))
        #expect(tally.counts.count == expected)
        #expect(tally.words == 3)
    }

    @Test func keepsAccentedWordsWhole() {
        let tally = Tally.of("Ẹ̀kọ́ dára. ẹ̀kọ́!")
        #expect(tally.words == 3)
        #expect(tally.top(1).first?.word == "ẹ̀kọ́")
    }
}

@Suite struct TextFilesTests {
    @Test func findsMatchingFilesInSubfolders() throws {
        let fileManager = FileManager.default
        let folder = fileManager.temporaryDirectory.appending(path: "wordtally-\(UUID().uuidString)")
        try fileManager.createDirectory(at: folder.appending(path: "sub"), withIntermediateDirectories: true)
        defer { try? fileManager.removeItem(at: folder) }
        try "one".write(to: folder.appending(path: "a.txt"), atomically: true, encoding: .utf8)
        try "two".write(to: folder.appending(path: "sub/B.TXT"), atomically: true, encoding: .utf8)
        try "three".write(to: folder.appending(path: "c.csv"), atomically: true, encoding: .utf8)

        let files = try TextFiles.expand([folder.path(percentEncoded: false)], extensions: ["txt"])
        #expect(files.map { URL(filePath: $0).lastPathComponent }.sorted() == ["B.TXT", "a.txt"])
    }

    @Test func reportsAMissingPath() {
        #expect(throws: TallyError.notFound("no-such-file")) {
            try TextFiles.expand(["no-such-file"], extensions: ["txt"])
        }
    }
}
SWIFT
swift test

A few things to notice:

  • The tests import WordTallyCore without @testable, so they can only use what is public, the same as any other code that uses the library.
  • The arguments: test is parameterised: it runs once for each pair, and a failure report names the pair that failed.
  • #expect(throws:) passes only if the closure throws that exact error.
  • The folder test builds its own files under FileManager.default.temporaryDirectory (/tmp on Ubuntu, a per-user folder on a Mac) and removes them with defer, so it runs the same on both systems and leaves nothing behind. It also checks that B.TXT, with an upper-case extension, is found on a case-sensitive file system.

Swift Testing runs tests in parallel by default. That is safe here because no test shares mutable state with another, for the same reason the compiler insisted on in the last step.

Check it worked

swift test ends with a line like Test run with 6 tests in 2 suites passed, with a tick next to each test above it. To see a failure, change == 14 to == 15 in the first test and run swift test again: the report shows tally.characters → 14 against 15. Change it back afterwards.

Step 7 · Build a release binary and install it

Debug builds compile quickly and run slowly. Build the optimised version:

Bash
cd ~/wordtally-demo
swift build -c release
ls -lh .build/release/wordtally
ldd .build/release/wordtally

ldd lists the shared libraries the binary needs. On Linux you will see Swift libraries such as libswiftCore.so and Foundation's libFoundation.so among others from the Swift toolchain. A machine without Swift installed does not have them, so this binary only runs where Swift is installed.

Build it again with the Swift runtime linked in:

Bash
swift build -c release --static-swift-stdlib
ls -lh .build/release/wordtally
ldd .build/release/wordtally

The binary is larger, and ldd no longer lists libswiftCore.so, Foundation or the other Swift libraries; what is left are system libraries such as libc.so.6. You can copy it to another Linux machine with a similar or newer C library (another Ubuntu 26.04 server, for example) and run it there without installing Swift. For a binary with no dependencies at all, even on the C library, the Swift project publishes a Static Linux SDK; its getting-started guide on swift.org covers it.

Install it for your user:

Bash
mkdir -p ~/.local/bin
install -m 755 .build/release/wordtally ~/.local/bin/wordtally
~/.local/bin/wordtally --version

On Ubuntu, ~/.local/bin is added to your PATH at login once the folder exists, so after you open a new login shell you can type wordtally from anywhere. This copy does not update itself: to upgrade, rebuild and run the install line again.

Check it worked

~/.local/bin/wordtally --version prints 0.1.0, and the second ldd output has no libswiftCore or libFoundation lines. Try wordtally ~/wordtally-demo/samples -t 1 from another folder to see it run.

Step 8 · Remove the demo

When you have finished, this deletes the project folder, including the downloaded library, and the installed binary:

Bash
rm -rf ~/wordtally-demo
rm -f ~/.local/bin/wordtally

Check it worked

ls ~/wordtally-demo reports that there is no such file or directory, and command -v wordtally prints nothing.

Next steps

Ideas to extend wordtally: add a --json flag that prints the totals with JSONEncoder, or a --stop-words option that reads a file of words to leave out of the top list.

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.