Project Icon

SwiftFormat

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

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

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
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号