skip to content

SwiftFormat

SwiftFormat rewrites Swift layout from a .swiftformat file of rules and options, or only reports in lint mode. Interviewers ask how it splits work with SwiftLint when a project runs both.

on this pageshow

explore

questions

6

In SwiftFormat, how does a .swiftformat file choose rules and options, and how does the tool find the file that applies?

level: juniorimportance: should knowfreq 40%

answer

  1. command-line flags, one per line
  2. rules rewrite code, options tune them
  3. --rules is an exclusive list
  4. nested folder's file overrides its parent
  5. --config ignores local files, --base-config keeps them

basics

~10 s

A .swiftformat file is SwiftFormat command-line arguments written one per line: --rules, --disable and --enable pick rules, other flags set options. SwiftFormat applies every .swiftformat on the path to each file, deeper ones overriding.

solid answer

~40 s

SwiftFormat separates **rules**, which rewrite code, from **options**, which tune what the rules do. A `.swiftformat` file is simply command-line arguments, one per line, with `#` comments: `--indent 4`, `--disable redundantSelf`, `--enable isEmpty`, `--exclude Generated`. `--rules a,b` runs only the listed rules, which also keeps rules added by a future release switched off; `--disable` removes rules from the default set and `--enable` adds opt-in ones. As it walks the path to each input file, SwiftFormat applies every directory's `.swiftformat`, so a nested file overrides its parents for that subtree, and `--exclude` paths resolve from the file that lists them. Passing `--config path` uses that file and ignores the local `.swiftformat` files; `--base-config` uses one without ignoring them.

code

bash · 8 lines
bash
# Root .swiftformat applies to the whole project; Tests/.swiftformat overrides it below Tests/
swiftformat .

# Only ci.swiftformat applies; local .swiftformat files are ignored
swiftformat --config ci.swiftformat .

# Shared base file, local .swiftformat files still applied on top
swiftformat --base-config ../shared.swiftformat .

go deeper

for a junior

Recall that the file is plain command-line flags, one per line, and that rules and options are different things. Be able to disable one rule and set the indent.

for a middle

Explain the order --rules, --disable, --enable and --lint-only apply in, how nested files override their parents, and why --exclude is relative to its own file.

for a senior

Show you know --config ignores local files while --base-config keeps them, and use --rules or --min-version so an upgrade never reformats code in an unrelated pull request.

for a principal

Weigh an exclusive --rules list, which needs deliberate upgrades, against tracking each release's defaults, which keeps style current but costs reformatting churn.

## Rules and options SwiftFormat's configuration has two kinds of setting, and mixing them up is the usual source of confusion. - **Rules** are the functions that rewrite code: `indent`, `braces`, `trailingCommas`, `redundantSelf`, `consecutiveSpaces` and well over a hundred more. Most are enabled by default; a smaller set, such as `isEmpty`, `markTypes` and `organizeDeclarations`, is opt-in. - **Options** are values the rules read, such as `--indent 4`, `--allman false`, `--self remove` or `--max-width 120`. One option can affect several rules, and an option has no effect when the rules that read it are disabled. `swiftformat --rules` with no value lists every rule and marks each one as enabled by default, disabled by default or deprecated; `--rule-info trailingCommas` shows which options a rule reads; `--options` lists every option with its default. ## What the file looks like A `.swiftformat` file is not YAML or JSON. It is the same arguments you would type on the command line, split onto separate lines, with blank lines and `#` comments allowed: ```plaintext # layout --indent 4 --max-width 120 # rules --disable redundantSelf --enable isEmpty # files --exclude Generated,Fixtures/**/*.swift ``` `swiftformat --infer-options . --output .swiftformat` writes a starting file inferred from the existing code, which is a gentler first step than adopting every default at once. ## Choosing rules: three flags that combine | Flag | Starting set | Effect | |---|---|---| | `--rules a,b` | only the listed rules | an exclusive list; rules added by a later release stay off | | `--disable a,b` | the default set | removes rules; `--disable all` removes every rule | | `--enable a,b` | the default set | adds opt-in rules; `--enable all` adds every rule | SwiftFormat applies them in a fixed order: 1. If `--rules` is present, its list replaces the default set. 2. `--disable` then removes rules from that set. 3. `--enable` then adds rules back, so `--disable all` followed by `--enable indent,linebreaks` leaves exactly those two. 4. `--lint-only` rules are added in `--lint` mode and removed in a normal run. A team that wants no surprises at upgrade time writes an explicit `--rules` list, or `--disable all` plus `--enable`; a team that wants each release's new rules writes only `--disable` for the ones it rejects. Since 0.63.0 SwiftFormat warns when `--enable` names a rule that is already on by default. ## How SwiftFormat finds the file that applies For each input file, SwiftFormat walks the directories on its path from the top down and reads the `.swiftformat` it meets in each one. - Each file's settings are merged over what came before, so `Tests/.swiftformat` with `--indent 2` overrides a root file's `--indent 4` for everything under `Tests/`. - Formatting options and rule flags given on the command line are applied on top of what the files say. - `--exclude` takes a comma-delimited list of paths or globs, resolved relative to the `.swiftformat` file that lists them, not to the directory you ran the command from. - Since 0.64.0, directories named `.build`, `Build` and `DerivedData` are excluded by default; `--unexclude Build` brings one back. - One file can also hold sections headed `[Tests]`, each with a `--filter` glob such as `**/Tests/**`, whose options apply only to matching files. `--config path/to/file` changes the discovery rule: SwiftFormat uses the named file (which need not be called `.swiftformat`, and may sit outside the project) and ignores the `.swiftformat` files it finds while walking. `--base-config` loads a shared file but keeps honouring the local ones, so per-folder overrides still work. ## Guard rails for a shared file - `--min-version 0.64.0` makes an older binary stop with "Project specifies SwiftFormat --min-version of 0.64.0" instead of formatting with different rules. - An unknown rule or option name is an error by default; `--unknown-options warn` or `ignore`, added in 0.64.0, lets one file serve several SwiftFormat versions. - Options have been spelled in kebab-case since 0.57.0, such as `--swift-version`, `--max-width` and `--lint-only`; the older run-together names still parse. ## Checking which file applied - SwiftFormat logs each config file it reads ("Reading config file at ...") and each one it skips ("Ignoring config file at ..."), which is the quickest way to see why a folder formats differently. - When piping code through standard input, SwiftFormat cannot see the file's location, so it cannot find the right `.swiftformat`; pass `--stdin-path` with the real path, as a pre-commit hook script does. - `--verbose` adds which rules changed each file, which tells you what to `--disable` when a rule surprises you. Commit the `.swiftformat` file beside the Xcode project so the command line, a build phase and CI all read the same settings.

  • Why might a team write an explicit --rules list in its shared .swiftformat instead of only --disable?
    `--rules` is exclusive, so a rule added and enabled by default in a later SwiftFormat release stays off until someone adds it to the list. With only `--disable`, upgrading the binary switches every new default rule on, and an unrelated pull request suddenly reformats files. The cost is that improvements must be opted into one by one; `--disable all` followed by `--enable` gives the same effect.
  • Developers on the team run different SwiftFormat versions; what can the config file do about it?
    Add `--min-version 0.64.0` to `.swiftformat`. An older binary then stops with "Project specifies SwiftFormat --min-version of 0.64.0" and exit code 70 instead of formatting differently. It sets a floor, not a pin, so the build phase or CI should still fetch one fixed release for everyone.

  • A .swiftformat file is YAML, like SwiftLint's configuration file.
  • Only the .swiftformat at the repository root is ever read.
  • --rules indent adds indent while every other default rule keeps running.
  • --config adds the named file on top of the local .swiftformat files.
  • --exclude paths resolve from the directory where swiftformat was launched.

Assumes SwiftFormat 0.64.0, which began excluding .build, Build and DerivedData by default and added --unknown-options for configs shared across versions.

open as a page

In SwiftFormat, how do swiftformat:disable, :next and swiftformat:options comments keep a hand-aligned table of Swift constants from being reformatted?

level: middleimportance: should knowfreq 30%

basics

~10 s

Wrap the table in // swiftformat:disable consecutiveSpaces and // swiftformat:enable consecutiveSpaces, or use // swiftformat:disable:next for one line. swiftformat:options changes option values for part of a file instead of switching rules off.

open as a page

What does SwiftFormat's --lint mode do differently from a normal run, and what do --lenient and its exit codes mean for a CI step?

level: middleimportance: should knowfreq 38%

basics

~20 s

With --lint, SwiftFormat formats each file in memory, writes nothing, reports every line that would change and exits 1 if any file needs formatting. --lenient keeps the report but exits 0; exit 70 means bad input or configuration.

open as a page

Why should a project give SwiftFormat its Swift version with --swift-version or a .swift-version file, and what goes wrong without one?

level: middleimportance: should knowfreq 28%

basics

~20 s

Some SwiftFormat rules produce syntax only newer Swift accepts, so with no version set they stay off and every run warns. Declare the oldest Swift compiler that builds the project with --swift-version or a .swift-version file.

open as a page

A project runs SwiftFormat and SwiftLint, and trailing commas and multiline opening braces keep flipping between builds; why, and how do you stop it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Both tools have layout rules with opposite defaults: SwiftFormat adds trailing commas and moves a multiline statement's brace onto its own line, while SwiftLint's trailing_comma and opening_brace want the reverse. Give each concern one owner and align the other.

open as a page

How do SwiftFormat's Xcode source editor extension, a Run Script build phase and its command plugin differ in which configuration they use and when they run?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

The source editor extension formats the open file on demand using rules stored in its host app, not the project's .swiftformat. A Run Script phase runs the CLI on every build; the command plugin only when invoked.

open as a page