在 Cursor / VS Code 中安装 swift-format 扩展

了解如何在 Cursor 中安装 swift-format 扩展,并配置保存时自动应用格式化。

在 Cursor / VS Code 中安装 swift-format 扩展

在 Cursor 或 VS Code 中安装 Swift 语言格式化工具,以便自动调整 Swift 代码缩进,提高可读性。

常用于 Swift 语言的格式化工具有两个:

  • swift-format:苹果官方工具,已内置于 Xcode 16 及以上版本中。
  • SwiftFormat:社区工具,也是非常强大的工具。

我选择使用 swift-format,以便和 Xcode 保持一致。

安装 apple-swift-format 插件

在扩展中搜索 apple-swift-format 插件并安装:

安装 swift-format 工具

apple-swift-format 扩展只是用于调用 swift-format 的桥梁,要实现代码格式化,还需要安装 swift-format 工具。

GitHub - swiftlang/swift-format: Formatting technology for Swift source code
Formatting technology for Swift source code. Contribute to swiftlang/swift-format development by creating an account on GitHub.

swift-format 是 Swift 语言官方格式化工具

推荐通过 Homebrew 来安装 swift-format:

brew install swift-format

使用 apple-swift-format 格式化代码

安装完成后,在 Cursor 或 VS code 中,右键选择「格式化文档」,或者使用快捷键 Option + Command +L 即可自动格式化代码:

0:00
/0:04

配置保存代码时自动格式化

配置自动格式化代码,能进一步减少负担。

在设置中,勾选 Format On Save 选项,即可在每次保存代码时自动应用格式化: