1. 安裝 swiftformat
brew install swiftformat
2. 安裝 swiftformat Xcode插件
brew install --cask swiftformat-for-xcode
3. 打開swiftformat
在程序塢中直接打開
或
open "/Applications/SwiftFormat For Xcode.app"
會(huì)看到 About疹鳄, 介紹了 How do I install it?
4. 開啟權(quán)限
設(shè)置->隱私與安全性->擴(kuò)展
選擇Xcode Source Editor鱼鼓,勾選SwiftFormat
5. 重啟Xcode
點(diǎn)擊 頂部 Editor目錄可以看到 SwiftFormat, 可以手動(dòng)格式化單個(gè)文件或選中內(nèi)容
6. 配置快捷鍵
參考 http://www.reibang.com/p/69883f2a16e1
7. 格式化代碼
在項(xiàng)目目錄批量格式化可以執(zhí)行
swiftformat .
單個(gè)文件
swiftformat path/file.swift
8. 自動(dòng)格式化代碼
8.1 創(chuàng)建鉤子目錄
mkdir -p .git/hooks
8.2 創(chuàng)建 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 賦予執(zhí)行權(quán)限
chmod +x pre-commit
完成以上步驟揭鳞,提交代碼的時(shí)候會(huì)自動(dòng)format