SwiftFormat

SwiftFormat

多平台Swift代码格式化工具 支持命令行和IDE集成

SwiftFormat是一款跨平台Swift代码格式化工具,支持macOS、Linux和Windows。它能自动调整代码空白、处理隐式self、删除冗余括号,并纠正不符合Swift标准习惯的用法。SwiftFormat可作为命令行工具使用,也可集成到Xcode、CI流程或版本控制系统中。这种自动化的代码格式化方案让开发者可以更专注于代码逻辑,而非样式细节。

SwiftFormat代码格式化Swift命令行工具Xcode插件Github开源项目

PayPal Build Codecov Swift 5.1 License Mastodon

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:

  1. As a command-line tool that you run manually, or as part of some other toolchain
  2. As a Source Editor Extension that you can invoke via the Editor > SwiftFormat menu within Xcode
  3. As a build phase in your Xcode project, so that it runs every time you press Cmd-R or Cmd-B, or
  4. 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:

  1. open SwiftFormat.xcodeproj and build the SwiftFormat (Application) scheme.

  2. 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).

  3. 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).

  4. 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).

  5. 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:

  1. Choose a file or directory that you want to apply the changes to.

  2. Make sure that you have committed all your changes to that code safely in git (or whatever source control system you use).

  3. (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.

  4. 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.

  5. 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.

  6. (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

  1. Create a folder called BuildTools in the same folder as your xcodeproj file
  2. 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: "")] )
  1. If you are running Xcode 11.4 or later, in the BuildTools folder create a file called Empty.swift with nothing in it. This is to satisfy a change in Swift Package Manager.

2) Add a Build phase to your app target

  1. Click on your project in the file list, choose your target under TARGETS, click the Build Phases tab

  2. Add a New Run Script Phase by clicking the little plus icon in the top left

  3. Uncheck the Based on dependency analysis checkbox

  4. 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.

Using CocoaPods

1) Add the SwiftFormat CLI to your Podfile

  1. 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".

2) Add a Build phase to your app target

  1. Click on your project in the file list, choose your target under TARGETS, click the Build Phases tab

  2. Add a New Run Script Phase by clicking the little plus icon in the top left

  3. Uncheck the Based on dependency analysis checkbox

  4. Drag the new Run Script phase above the Compile 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

编辑推荐精选

讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

TRELLIS

TRELLIS

用于可扩展和多功能 3D 生成的结构化 3D 潜在表示

TRELLIS 是一个专注于 3D 生成的项目,它利用结构化 3D 潜在表示技术,实现了可扩展且多功能的 3D 生成。项目提供了多种 3D 生成的方法和工具,包括文本到 3D、图像到 3D 等,并且支持多种输出格式,如 3D 高斯、辐射场和网格等。通过 TRELLIS,用户可以根据文本描述或图像输入快速生成高质量的 3D 资产,适用于游戏开发、动画制作、虚拟现实等多个领域。

下拉加载更多