Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 146 ยท Platforms and Ecosystem

SwiftLint, swift-format and DocC

Set up Swift style and documentation tooling: SwiftLint rules and config, swift-format and its JSON settings, DocC catalogs and hosting, plus CI and SwiftPM integration.

A team of one can keep a codebase tidy by habit. A team of ten cannot. Sooner or later someone argues about brace placement in a code review, someone force-unwraps a value that should never be nil, and nobody can find out what a public function promises. Three tools solve these problems and have become standard in the Swift world:

  • SwiftLint reports (and sometimes fixes) style and correctness smells: force casts, long functions, unused variables.
  • swift-format rewrites code into one canonical layout: indentation, line breaks, spacing, trailing commas.
  • DocC builds documentation websites from your doc comments and extra articles.

All three run on the command line, so they work in Xcode, in editors such as VS Code, on Linux and in continuous integration. They are not part of the program you ship; they are part of the pipeline that builds it. That is why the commands here are shown as read-only blocks, while the TryIt examples teach the ideas behind them with plain Swift that runs on this site.

flowchart LR
    E["Edit code"] --> F["swift-format<br/>fixes layout"]
    F --> L["SwiftLint<br/>checks rules"]
    L --> B["Build + test"]
    B --> D["DocC<br/>builds docs"]
    D --> P["Publish docs"]
    L -->|"violation"| X["Fail the pull request"]

A typical pipeline: format, lint, build, document. Each step is a command that can fail the build.

Formatter or linter: what is the difference?

They overlap, which confuses people at first. The rule of thumb:

Formatter (swift-format) Linter (SwiftLint)
Question "Is the code laid out the standard way?" "Does the code follow our rules?"
Changes your code Yes, always the same way Only for the rules that can auto-fix
Typical findings Wrong indentation, line too long, missing trailing comma force_cast, cyclomatic_complexity, identifier_name
Opinion Almost none: layout is mechanical Many: you choose and tune rules

Use the formatter so nobody ever discusses whitespace again, and the linter to enforce the conventions that need judgment.

SwiftLint

SwiftLint is an open source tool from the Realm team (now maintained by the community) that parses your code with SwiftSyntax and checks it against a long list of rules. Install it with Homebrew (brew install swiftlint), through Mint, as a prebuilt binary from its GitHub releases, or as a SwiftPM plugin.

Terminal
swiftlint                    # lint the current folder, print warnings and errors
swiftlint lint --strict      # treat every warning as an error (good for CI)
swiftlint --fix              # apply automatic corrections for rules that support it
swiftlint rules              # list all rules and whether they are enabled
swiftlint lint --reporter github-actions-logging

Output looks like a compiler diagnostic, so Xcode and editors can underline the exact line:

TEXT
Sources/App/Parser.swift:42:17: warning: Force Cast Violation: Force casts should be avoided. (force_cast)

The .swiftlint.yml file

SwiftLint reads .swiftlint.yml from the project root. This is a realistic configuration:

YAML
included:
  - Sources
  - Tests
excluded:
  - .build
  - Sources/Generated

disabled_rules:
  - trailing_whitespace      # the formatter handles this
opt_in_rules:                # rules that are off by default
  - empty_count
  - first_where
  - sorted_first_last
  - unused_import
analyzer_rules:              # need a full compile log: swiftlint analyze
  - unused_declaration

line_length:
  warning: 120
  error: 160
  ignores_urls: true
  ignores_comments: true

function_body_length:
  warning: 50
  error: 100

identifier_name:
  min_length: 2
  excluded: [id, x, y, i, j]

custom_rules:
  no_print:
    name: "No print"
    regex: '\bprint\('
    message: "Use the logger instead of print."
    severity: warning

Key ideas:

  • Default rules are the safe set that is on without any configuration. Opt-in rules need to be listed in opt_in_rules. Analyzer rules need a compile log and run with swiftlint analyze --compiler-log-path build.log.
  • A rule's own settings (line_length, function_body_length) are a warning and an error threshold. A lone number sets only the warning.
  • Nested configuration files work: a .swiftlint.yml in a subfolder overrides the parent for that subtree. This helps in monorepos and for test folders that deserve looser rules.
  • custom_rules are regular expressions. They are quick to write, but regexes are blunt, so prefer a built-in rule when one exists.

Common rules and what they teach

Rule What it flags Better
force_cast value as! Dog guard let dog = value as? Dog
force_try try! load() do { try ... } catch { ... }
force_unwrapping (opt-in) name! if let, guard let, ??
empty_count (opt-in) array.count == 0 array.isEmpty
first_where (opt-in) filter { ... }.first first(where: ...)
cyclomatic_complexity a function with too many branches split it
identifier_name one-letter names, snake_case descriptive camelCase
todo TODO and FIXME comments link them to an issue
unused_closure_parameter { x in 42 } { _ in 42 }

See errors and optionals in depth for why the force rules matter.

Turning a rule off in one place

Sometimes the rule is right in general but wrong right here. Say so explicitly and keep the exception small:

Swift
// swiftlint:disable:next force_cast
let layout = collectionView.collectionViewLayout as! GridLayout

// swiftlint:disable cyclomatic_complexity
func parse(_ token: Token) -> Node {
    // ... a big switch that really is one decision per case ...
}
// swiftlint:enable cyclomatic_complexity

The variants are disable:next, disable:this, disable:previous and a plain disable / enable pair. A comment explaining why helps the next reader.

Seeing the idea: a tiny lint pass

SwiftLint is not available in the runner on this site, but a linter is just a program that reads source text and reports locations. This miniature version implements three rules over a string, so you can see how violations are found and reported:

Swift A miniature linter

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.

Real SwiftLint parses a syntax tree instead of searching text, so it never confuses as! inside a string literal or comment with a real cast. The report format and the way each rule has an identifier are the same idea.

Running SwiftLint with Swift Package Manager and Xcode

  • Xcode build phase. Add a Run Script phase that runs swiftlint. Violations show up inline as yellow and red marks. Wrap it in if command -v swiftlint >/dev/null; then ... fi so teammates without it can still build.
  • SwiftPM plugin. The SwiftLintPlugins package provides build tool plugins that fetch a prebuilt binary and run it during swift build (see Swift Package Manager). Add the package as a dependency and list the plugin in a target's plugins: array.
  • Pre-commit hook or CI step. Run swiftlint lint --strict in a pull request job, so the check cannot be skipped. SwiftLint has reporters for GitHub Actions, JSON, Checkstyle and others.

When you first adopt SwiftLint on an old codebase, you will see thousands of warnings. Use swiftlint lint --write-baseline baseline.json once, then --baseline baseline.json afterwards, so only new violations fail the build, and fix the old ones gradually.

swift-format

swift-format is the official formatter from the Swift project. It uses SwiftSyntax too, and since Swift 6 it ships inside the toolchain as the swift format subcommand, so there is nothing to install on a machine with Xcode or a Swift 6 toolchain. (Older setups install the package swift-format with Homebrew or build it from source and call swift-format directly.)

Terminal
swift format lint -r Sources Tests          # report issues, change nothing
swift format format -i -r Sources Tests     # rewrite files in place
swift format dump-configuration > .swift-format   # print the default settings

lint is for CI, format -i is for local use. Both walk folders when you pass -r (recursive).

Configuration

Settings live in a JSON file called .swift-format that the tool looks for next to the source, then in parent folders:

JSON
{
  "version": 1,
  "lineLength": 100,
  "indentation": { "spaces": 4 },
  "tabWidth": 4,
  "maximumBlankLines": 1,
  "respectsExistingLineBreaks": true,
  "lineBreakBeforeEachArgument": false,
  "lineBreakBeforeControlFlowKeywords": false,
  "multiElementCollectionTrailingCommas": true,
  "rules": {
    "AlwaysUseLowerCamelCase": true,
    "NeverForceUnwrap": false,
    "UseTripleSlashForDocumentationComments": true
  }
}

Layout options (lineLength, indentation, maximumBlankLines) control how code is formatted. The rules map turns individual lint-style checks on or off; some of them (like UseTripleSlashForDocumentationComments or OrderedImports) are rewritten automatically by format, while others (NeverForceUnwrap) can only be reported.

Seeing the idea: formatting is a pure function

A formatter takes text in and returns canonical text. Because the result depends only on the input and the settings, running it twice changes nothing (it is idempotent), and every machine produces the same output. The tiny formatter below fixes three things (trailing spaces, tab indentation, runs of blank lines) and proves the idempotence:

Swift A miniature formatter

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 real tool also understands syntax, so it can decide where to break a long argument list, and it knows that changing the spacing inside a string literal would change the program.

Formatter and linter together

Both SwiftLint and swift-format can complain about the same thing, such as line length. Pick one tool as the owner of each concern. A common split: swift-format owns layout, and SwiftLint has its layout rules (trailing_whitespace, vertical_whitespace, line_length auto-fixing) disabled, keeping only its semantic rules. Another popular formatter is SwiftFormat by Nick Lockwood (a different project with a similar name and its own configuration file); the same advice applies.

DocC

Documentation comments turn into pages with DocC, the documentation compiler from Apple, which is open source and works on Linux too. DocC reads three inputs: the /// comments in your code, a documentation catalog (a folder ending in .docc) with extra articles and images, and the symbol graph the compiler emits for your public API.

flowchart LR
    S["Swift source<br/>with /// comments"] --> G["Symbol graph<br/>(public API)"]
    C["Catalog .docc<br/>articles, images, tutorials"] --> D["DocC compiler"]
    G --> D
    D --> A[".doccarchive"]
    A --> W["Static website"]
    A --> X["Xcode documentation viewer"]

DocC combines the symbol graph of your public API with the articles in a .docc catalog and produces an archive that you can host or open in Xcode.

Building documentation

Terminal
# In Xcode: Product > Build Documentation (Ctrl+Shift+Cmd+D)

# With SwiftPM, after adding the swift-docc-plugin package as a dependency:
swift package generate-documentation
swift package --disable-sandbox preview-documentation --target MyLibrary

# Static site for GitHub Pages, served under /my-library/
swift package --allow-writing-to-directory ./docs \
  generate-documentation --target MyLibrary \
  --disable-indexing --transform-for-static-hosting \
  --hosting-base-path my-library --output-path ./docs

preview-documentation starts a local server that reloads when you edit a comment. DocC only documents public (or open) symbols by default, which matches the idea that documentation describes an API, not its internals; see access control.

The catalog

A catalog is just a folder next to your sources, for example Sources/MyLibrary/MyLibrary.docc:

TEXT
MyLibrary.docc/
  MyLibrary.md             landing page (the "documentation extension" for the module)
  GettingStarted.md        an article
  Resources/
    architecture.png

The landing page is Markdown with a few DocC directives. Its first heading is the module name in double backticks, and a ## Topics section groups the symbols you want people to find:

MARKDOWN
# ``MyLibrary``

Fast, tiny helpers for working with schedules.

## Overview

MyLibrary turns a list of events into non-overlapping time slots. Start with
<doc:GettingStarted>, then read about ``Schedule``.

## Topics

### Essentials

- <doc:GettingStarted>
- ``Schedule``
- ``Event``

### Errors

- ``ScheduleError``

Linking rules:

  • Double backticks link to a symbol: ``Schedule``, or a member such as ``Schedule/add(_:)``.
  • <doc:GettingStarted> links to an article by file name.
  • A symbol you leave out of every ## Topics list still appears, under an automatic group.
  • DocC warns about links that do not resolve. Treat those warnings as errors in CI so documentation cannot rot unnoticed.

Writing articles and tutorials

Articles are plain Markdown files, and good ones answer a question ("How do I add a recurring event?"). DocC also supports tutorials: step-by-step guided lessons with @Tutorial, @Steps and @Code directives, where each step shows the code file growing. They are what Apple's own SwiftUI tutorials use. Start with articles; add tutorials only for a long onboarding path.

Directives for a nicer landing page include @Metadata { @TechnologyRoot } (makes an article the root of a catalog that has no code), @PageImage, and @Row/@Column for layouts. You can also add @Snippet(path: "MyLibrary/Snippets/addEvent") to include a compiled example from a Snippets folder, so the sample in the docs is always checked by the compiler.

Documenting well

  • Write a one-sentence summary first. It becomes the subtitle in listings.
  • Use - Parameter, - Returns and - Throws for the contract, and a > Note: or > Warning: aside for traps.
  • Document why and what it promises, not the obvious. /// Returns the name on var name adds noise.
  • Keep examples short, and prefer snippets that the compiler checks.

Putting it into a team workflow

  1. Commit .swiftlint.yml and .swift-format so everyone shares one standard.
  2. Run swift format format -i on save in your editor (or before committing with a pre-commit hook).
  3. In CI, run swift format lint -r, swiftlint lint --strict, then build and test, then generate-documentation.
  4. Publish the static site from the main branch (GitHub Pages, Netlify or your own server). The Swift Package Index also builds DocC documentation for open source packages automatically when you add a .spi.yml file.
  5. Review the tools' configuration like code: a rule that everybody silences with // swiftlint:disable is a rule to remove or fix.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between swift-format and SwiftLint?

    A formatter is mostly mechanical and changes layout the same way every time. A linter checks opinionated rules (force casts, complexity, naming), and only some violations are auto-fixable.
  2. 2. Which command makes SwiftLint fail the build when it finds any warning?

    --strict treats warnings as errors, which makes it suitable for a CI step. --fix rewrites code, rules lists rules, and analyze runs analyzer rules.
  3. 3. How do you silence a single SwiftLint rule for exactly the next line?

    The disable:next comment (also this, previous, and enable/disable pairs) limits the exception to a small, visible place.
  4. 4. In a DocC catalog, how do you link to an article named GettingStarted.md?

    doc:Name links to articles; double backticks link to symbols such as types and methods.
  5. 5. Why is it useful that a formatter is idempotent?

    If format(format(x)) equals format(x), running the formatter in an editor, a hook and CI never fights with itself, and lint can simply verify nothing would change.

Summary

  • Use a formatter (swift-format, shipped with the Swift 6 toolchain as swift format) for layout and a linter (SwiftLint) for rules that need judgment. Give each concern one owner.
  • Configure SwiftLint in .swiftlint.yml: included/excluded, disabled_rules, opt_in_rules, rule thresholds and custom_rules. Silence exceptions locally with // swiftlint:disable:next rule.
  • Configure swift-format with a JSON .swift-format file; use lint in CI and format -i locally.
  • DocC builds documentation from /// comments plus a .docc catalog: symbol links use double backticks, article links use <doc:Name>, and ## Topics organizes the page.
  • Put all three into CI with --strict, a baseline for legacy code, and warnings treated as errors, so quality does not depend on memory.

Next: Swift Cheat Sheet