1. 安裝 swiftformat
brew install swiftformat
2. 安裝 swiftformat Xcode插件
brew install --cask swiftformat-for-xcode
3. 打開swiftformat
在程序塢中直接打開
或
open "/Applications/SwiftFormat For Xcode.app"
會看到 About, 介紹了 How do I install it?
4. 開啟權限
設置->隱私與安全性->擴展
選擇Xcode Source Editor,勾選SwiftFormat
5. 重啟Xcode
點擊 頂部 Editor目錄可以看到 SwiftFormat, 可以手動格式化單個文件或選中內容
6. 配置快捷鍵
參考 http://www.lxweimin.com/p/69883f2a16e1
7. 格式化代碼
在項目目錄批量格式化可以執行
swiftformat .
單個文件
swiftformat path/file.swift
8. 自動格式化代碼
8.1 創建鉤子目錄
mkdir -p .git/hooks
8.2 創建 pre-commit 鉤子腳本
cd .git/hooks
touch pre-commit
8.3 編輯 pre-commit 腳本
#!/bin/bash
# Get the staged Swift files
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.swift$')
# Check if any Swift files are staged
if [[ -n $files ]]; then
# Format the staged Swift files using swiftformat
swiftformat $files --swiftversion 5
# Add the formatted files to the staging area
git add $files
fi
8.4 賦予執行權限
chmod +x pre-commit
完成以上步驟,提交代碼的時候會自動format