Table of Contents
What is this?
SwiftFormat is a code library and command-line tool for reformatting Swift code on macOS, Linux or Windows.
SwiftFormat goes above and beyond what you might expect from a code formatter. In addition to adjusting white space it can insert or remove implicit self
, remove redundant parentheses, and correct many other deviations from the standard Swift idioms.
Why would I want to do that?
Many programmers have a preferred style for formatting their code, and others seem entirely blind to the existing formatting conventions of a project (to the enragement of their colleagues).
When collaborating on a project, it can be helpful to agree on a common coding style, but enforcing that manually is tedious and error-prone, and can lead to arguments if some participants take it more seriously than others.
Having a tool to automatically enforce a common style eliminates those issues, and lets you focus on the behavior of the code, not its presentation.
How do I install it?
That depends - There are several ways you can use SwiftFormat:
- As a command-line tool that you run manually, or as part of some other toolchain
- As a Source Editor Extension that you can invoke via the Editor > SwiftFormat menu within Xcode
- As a build phase in your Xcode project, so that it runs every time you press Cmd-R or Cmd-B, or
- As a Git pre-commit hook, so that it runs on any files you've changed before you check them in
Command-line tool
NOTE: if you are using any of the following methods to install SwiftFormat on macOS 10.14.3 or earlier and are experiencing a crash on launch, you may need to install the Swift 5 Runtime Support for Command Line Tools. See known issues for details.
Installation:
You can install the swiftformat
command-line tool on macOS or Linux using Homebrew. Assuming you already have Homebrew installed, just type:
$ brew install swiftformat
To update to the latest version once installed:
$ brew upgrade swiftformat
Alternatively, you can install the tool on macOS or Linux by using Mint as follows:
$ mint install nicklockwood/SwiftFormat
Or if you prefer, you can check out and build SwiftFormat manually on macOS, Linux or Windows as follows:
$ git clone https://github.com/nicklockwood/SwiftFormat
$ cd SwiftFormat
$ swift build -c release
If you are installing SwiftFormat into your project directory, you can use CocoaPods on macOS to automatically install the swiftformat binary along with your other pods - see the Xcode build phase instructions below for details.
Another option is to include the binary artifactbundle in your Package.swift
:
.binaryTarget(
name: "swiftformat",
url: "https://github.com/nicklockwood/SwiftFormat/releases/download/0.53.9/swiftformat-macos.artifactbundle.zip",
checksum: "CHECKSUM"
),
If you would prefer not to use a package manager, you can build the command-line app manually:
-
open
SwiftFormat.xcodeproj
and build theSwiftFormat (Application)
scheme. -
Drag the
swiftformat
binary into/usr/local/bin/
(this is a hidden folder, but you can use the Finder'sGo > Go to Folder...
menu to open it). -
Open
~/.bash_profile
in your favorite text editor (this is a hidden file, but you can typeopen ~/.bash_profile
in the terminal to open it). -
Add the following line to the file:
alias swiftformat="/usr/local/bin/swiftformat --indent 4"
(you can omit the--indent 4
, or replace it with something else. Runswiftformat --help
to see the available options). -
Save the
.bash_profile
file and run the commandsource ~/.bash_profile
for the changes to take effect.
Usage:
If you followed the installation instructions above, you can now just type
$ swiftformat .
(that's a space and then a period after the command) in the terminal to format any Swift files in the current directory. In place of the .
, you can instead type an absolute or relative path to the file or directory that you want to format.
WARNING: swiftformat .
will overwrite any Swift files it finds in the current directory, and any subfolders therein. If you run it in your home directory, it will probably reformat every Swift file on your hard drive.
To use it safely, do the following:
-
Choose a file or directory that you want to apply the changes to.
-
Make sure that you have committed all your changes to that code safely in git (or whatever source control system you use).
-
(Optional) In Terminal, type
swiftformat --inferoptions "/path/to/your/code/"
. This will suggest a set of formatting options to use that match your existing project style (but you are free to ignore these and use the defaults, or your own settings if you prefer).The path can point to either a single Swift file or a directory of files. It can be either be absolute, or relative to the current directory. The
""
quotes around the path are optional, but if the path contains spaces then you either need to use quotes, or escape each space with\
. You may include multiple paths separated by spaces. -
In Terminal, type
swiftformat "/path/to/your/code/"
. The same rules apply as above with respect to paths, and multiple space-delimited paths are allowed.If you used
--inferoptions
to generate a suggested set of options in step 3, you should copy and paste them into the command, either before or after the path(s) to your source files.If you have created a config file, you can specify its path using
--config "/path/to/your/config-file/"
. Alternatively, if you name the file.swiftformat
and place it inside the project you are formatting, it will be picked up automatically. -
Press enter to begin formatting. Once the formatting is complete, use your source control system to check the changes, and verify that no undesirable changes have been introduced. If they have, revert the changes, tweak the options and try again.
-
(Optional) commit the changes.
Following these instructions should ensure that you avoid catastrophic data loss, but in the unlikely event that it wipes your hard drive, please note that I accept no responsibility.
Using Standard Input/Output:
If you prefer, you can use unix pipes to include SwiftFormat as part of a command chain. For example, this is an alternative way to format a file:
$ cat /path/to/file.swift | swiftformat --output /path/to/file.swift
Omitting the --output /path/to/file.swift
will print the formatted file to Standard Output (stdout). You can also pass "stdout" explicitly as the output path:
$ cat /path/to/file.swift | swiftformat --output stdout
Or you can use >
to specify the output path as follows:
$ cat /path/to/file.swift | swiftformat > /path/to/file.swift
If you do not supply an input file, SwiftFormat will automatically take its input from Standard Input (stdin), but will time-out if no input is received immediately and display the help screen. To make it explicit, pass "stdin" as the input path:
$ cat /path/to/file.swift | swiftformat stdin
When using stdin, SwiftFormat does not have access to the file path of the input, so features that rely on the file location (such as inserting the creation date into header comments, or detecting .swiftformat
configuration files in the file path) will not work. To solve this, you can provide the file path using the --stdinpath
argument:
$ cat /path/to/file.swift | swiftformat stdin --stdinpath /path/to/file.swift
Xcode source editor extension
Installation:
Like the command-line tool, you can install the SwiftFormat for Xcode extension application via Homebrew. Assuming you already have Homebrew installed, type:
$ brew install --cask swiftformat-for-xcode
This will install SwiftFormat for Xcode in your Applications folder. Double-click the app to launch it, and then follow the on-screen instructions.
NOTE: The app should be correctly signed, but if you get a Gatekeeper warning when trying to open it you can bypass this by right-clicking (or control-clicking) the app and selecting Open
.
To update to the latest version once installed use:
$ brew upgrade --cask swiftformat-for-xcode
Alternatively, if you prefer not to use Homebrew, you'll find the latest version of the SwiftFormat for Xcode application on the GitHub Releases page. Download and unpack the zip archive, then drag SwiftFormat for Xcode.app
into your Applications
folder.
Usage:
Once you have launched the app and restarted Xcode, you'll find a SwiftFormat option under Xcode's Editor menu. If the SwiftFormat menu does not appear this thread may help.
You can configure the formatting rules and options using the SwiftFormat for Xcode host application. There is currently no way to override these per-project, however, you can import and export different configurations using the File menu. You will need to do this again each time you switch projects.
The format of the configuration file is described in the Config section below.
Note: SwiftFormat for Xcode cannot automatically detect changes to an imported configuration file. If you update the .swiftformat
file for your project, you will need to manually re-import that file into SwiftFormat for Xcode in order for the Xcode source editor extension to use the new configuration.
Xcode build phase
NOTE: Adding this script will overwrite your source files as you work on them, which has the annoying side-effect of clearing the undo history. You may wish to add the script to your test target rather than your main target, so that it is invoked only when you run the unit tests, and not every time you build the app.
Alternatively, you might want to consider running SwiftFormat in lint mode as part of your normal build, and then running a formatting pass manually, or as part of a less-frequent build target (such as the tests).
Using Swift Package Manager
To set up SwiftFormat as an Xcode build phase, do the following:
1) Create a BuildTools folder and Package.swift
- Create a folder called
BuildTools
in the same folder as your xcodeproj file - In this folder, create a file called
Package.swift
, with the following contents:
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "BuildTools",
platforms: [.macOS(.v10_11)],
dependencies: [
.package(url: "https://github.com/nicklockwood/SwiftFormat", from: "0.54.0"),
],
targets: [.target(name: "BuildTools", path: "")]
)
- If you are running Xcode 11.4 or later, in the
BuildTools
folder create a file calledEmpty.swift
with nothing in it. This is to satisfy a change in Swift Package Manager.
2) Add a Build phase to your app target
-
Click on your project in the file list, choose your target under
TARGETS
, click theBuild Phases
tab -
Add a
New Run Script Phase
by clicking the little plus icon in the top left -
Uncheck the
Based on dependency analysis
checkbox -
Drag the new
Run Script
phase above theCompile Sources
phase, expand it and paste the following script:cd BuildTools SDKROOT=(xcrun --sdk macosx --show-sdk-path) #swift package update #Uncomment this line temporarily to update the version used to the latest matching your BuildTools/Package.swift file swift run -c release swiftformat "$SRCROOT"
You can also use swift run -c release --package-path BuildTools swiftformat "$SRCROOT"
if you need a more complex script and cd BuildTools
breaks stuff.
NOTE: You may wish to check BuildTools/Package.swift into your source control so that the version used by your run-script phase is kept in version control. It is recommended to add the following to your .gitignore file: BuildTools/.build
and BuildTools/.swiftpm
.
NOTE (2): If you are using Xcode 15 or later, make sure that the ENABLE_USER_SCRIPT_SANDBOXING
(aka "User Script Sandboxing") option is set to NO, otherwise SwiftFormat won't be able to run correctly.
Using CocoaPods
1) Add the SwiftFormat CLI to your Podfile
-
Add the
swiftformat
binary to your project directory via CocoaPods, by adding the following line to your Podfile then runningpod install
:pod 'SwiftFormat/CLI', '~> 0.54'
NOTE: This will only install the pre-built command-line app, not the source code for the SwiftFormat framework.
NOTE (2): When installing this way, GateKeeper may block swiftformat from running until you open it manually the first time by right-clicking in the Finder and selecting "Open".
2) Add a Build phase to your app target
-
Click on your project in the file list, choose your target under
TARGETS
, click theBuild Phases
tab -
Add a
New Run Script Phase
by clicking the little plus icon in the top left -
Uncheck the
Based on dependency analysis
checkbox -
Drag the new
Run Script
phase above theCompile Sources
phase, expand it and paste the following script:"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" "$SRCROOT"
Alternative: Locally installed SwiftFormat
Alternatively, you could use a locally installed swiftformat command-line tool instead by putting the following in your Run Script build phase:
if which swiftformat >/dev/null; then
swiftformat .
else
echo "warning: SwiftFormat not installed, download from https://github.com/nicklockwood/SwiftFormat"
fi
This is not recommended for shared projects however, as different team members using different versions of SwiftFormat may result in noise in the commit history as code gets reformatted inconsistently.
If you installed SwiftFormat via Homebrew on Apple Silicon, you might experience this warning:
warning: SwiftFormat not installed, download from https://github.com/nicklockwood/SwiftFormat
That is because Homebrew on Apple Silicon installs the binaries into the /opt/homebrew/bin
folder by default. To instruct Xcode where to find SwiftFormat, you can either add
/opt/homebrew/bin
to the PATH
environment variable in your build phase
if [[ "$(uname -m)" == arm64 ]]; then
export