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.
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.
That depends - There are several ways you can use SwiftFormat:
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 the SwiftFormat (Application)
scheme.
Drag the swiftformat
binary into /usr/local/bin/
(this is a hidden folder, but you can use the Finder's Go > Go to Folder...
menu to open it).
Open ~/.bash_profile
in your favorite text editor (this is a hidden file, but you can type open ~/.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. Run swiftformat --help
to see the available options).
Save the .bash_profile
file and run the command source ~/.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
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.
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).
To set up SwiftFormat as an Xcode build phase, do the following:
BuildTools
in the same folder as your xcodeproj filePackage.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: "")] )
BuildTools
folder create a file called Empty.swift
with nothing in it. This is to satisfy a change in Swift Package Manager.Click on your project in the file list, choose your target under TARGETS
, click the Build 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 the Compile 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.
Add the swiftformat
binary to your project directory via CocoaPods, by adding the following line to your Podfile then running pod 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".
Click on your project in the file list, choose your target under TARGETS
, click the Build 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 the Compile Sources
phase, expand it and paste the following script:
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" "$SRCROOT"
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
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号