1. 下载 SwiftFormat

  • 通过brew命令安装
brew install swiftformat-for-xcode
  • 安装成功如下:
  • 查看是否安装成功

2. 安装 SwiftFormat 的 Xcode 插件和使用

$ brew install --cask swiftformat-for-xcode
$ open "/Applications/SwiftFormat For Xcode.app"
  • 插件安装成功
  • 打开刚刚安装的插件
  • 打开之后如下:
  • 打开【系统设置】点击【隐私与安全性】点击【Xcode Source Editor】
  • 选中SwiftFormat
  • 重启xcode,选择【Editor】选择【SwiftFormat】
    • Format Selection 处理选中的代码
    • Format File 处理当前文件

3. 添加自动化操作

  • 再【启动台】中找到【自动操作】打开,选择【快速操作】
  • 搜索Apple Script添加,将以下代码添加进去
    • 检查Xcode中Editor菜单下是否存在“SwiftFormat”>“Format File”菜单项。
    • 如果存在,则自动触发 Format File菜单点击,来格式化代码。
on run {input, parameters}
	tell application "System Events"
		tell process "Xcode"
			set frontmost to true
			if menu item "Format File" of menu of menu item "SwiftFormat" of menu "Editor" of menu bar 1 exists then
				click menu item "Format File" of menu of menu item "SwiftFormat" of menu "Editor" of menu bar 1
			end if
			click menu item "Save" of menu "File" of menu bar 1
		end tell
	end tell
	return input
end run
  • 如下:
  • 保存,取名:代码格式化_swift , 退出
  • 重新打开Xcode,会在 Xcode -> Services 菜单下看到它
  • 文件在 ~/Library/Services/ 目录下
# 打开上面设置的文件
$ open ~/Library/Services/

4. 添加快捷键

  • 打开 系统偏好设置 -> 键盘 -> 快捷键,选择 左侧 App快捷键 这一项,添加一个新的快捷键,应用程序选择 Xcode,添加Command + s 快捷键,名字和保存的快速操作名字一样
  • 运行报错,需要权限
  • 重启xcode 使用刚刚的快捷键,但是没反应,需要权限
    • 在系统设置->隐私与安全性->辅助功能
  • 辅助功能中勾选Xcode