Swift-CodeStyle Checker:SwiftLint
介紹:
SwiftLint 是一個用於強制檢查 Swift 代碼風格和規定的一個工具,基本上以 GitHub's Swift 代碼風格指南為基礎。
SwiftLint官網:
Github地址
SwiftLint中文博客(推薦):
Xcode代碼規范之SwiftLint配置
Swift代碼規范:
Github 公布的 Swift 代碼規范
Swift Version Support
這里有一份 SwiftLint 版本和對應該 Swift 版本的對照表作為參考。
Swift 版本 | 最后一個 SwiftLint 支持版本 |
---|---|
Swift 1.x | SwiftLint 0.1.2 |
Swift 2.x | SwiftLint 0.18.1 |
Swift 3.x | SwiftLint 0.25.1 |
Swift 4.0-4.1.x | SwiftLint 0.28.2 |
Swift 4.2.x-5.0 | 最新的 |
安裝
使用 Homebrew:
brew install swiftlint
XCode配置
安裝完成后,需要在Xcode中配置相關設置,才能使 SwiftLint 在 Xcode 中自動檢測代碼規范。配置也很簡單,只需要在 Xcode 的 Build Phases 中新建一個 Run Script Phase 配置項,在里面添加相關代碼后,編譯即可!
if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
多Xcode配置
如果有多個Xcode在同時使用,需要切換xcode的配置環境:
//切換到默認Xcode版本
sudo xcode-select -s '/Applications/Xcode.app/Contents/Developer'
//切換到其他Xcode版本
sudo xcode-select -s '/Applications/Xcode 10.1.app/Contents/Developer’
到這一步基本完成安裝和基礎的操作,正常運行Xcode即可獲得CodeStyle的檢查結果
自定義配置
除了通用的功能,我們還經常要做一些額外的事情,比如:去掉第三方庫的檢查、去掉或改變一些檢查規則等
新建自定義配置文件
打開終端, cd 到項目根目錄下
輸入: touch .swiftlint.yml
可以自定義的常用配置:
disabled_rules: # 禁用指定的規則
- colon
- comma
- control_statement
opt_in_rules: # 啟用指定的規則
- empty_count
- missing_docs
# 可以通過執行如下指令來查找所有可用的規則:
# swiftlint rules
included: # 執行 linting 時包含的路徑。如果出現這個 `--path` 會被忽略。
- Source
excluded: # 執行 linting 時忽略的路徑。 優先級比 `included` 更高。
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
忽略引入的第三方庫
在.swiftlint.yml文件中輸入
excluded:
- Pods
常用的規則修改項(簡單模板)
在.swiftlint.yml文件中輸入
excluded: # 執行 linting 時忽略的路徑。 優先級比 `included` 更高。
- Pods
disabled_rules: # 執行時排除掉的規則
- identifier_name # 命名規則必須按照駝峰原則,與后台傳的Json字段命名沖突,建議排除掉
- trailing_whitespace # 每一個空行不能有空格,會與Xcode換行后自動對齊生成的空格沖突,建議排除掉
force_cast: warning # 類型判斷
force_try: warning # try語句判斷
cyclomatic_complexity: 20 #代碼復雜度,默認為10
line_length: # 單行代碼長度,默認error 120
warning: 120
error: 200
file_length: # 文件長度
warning: 500
error: 1200
function_body_length: # 函數體長度
warning: 100
error: 300
這是一個基礎版本,隨着項目的開展,可分階段將規則逐漸嚴格起來