代碼風(fēng)格推薦
安裝和使用SwiftLint
- 第一步:先安裝homebrew
打開終端,輸入以下命令
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
- 第二步:安裝SwiftLint
brew install swiftlint
// 更新/升級(jí)SwiftLint到最新版本
brew upgrade swiftlint
- 第三步:Xcode添加腳本
if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
添加配置文件
(1) 第一步:在想要執(zhí)行代碼風(fēng)格檢查的文件夾新建一個(gè)名為.swiftlint.yml
的文件:cd 你要執(zhí)行檢查的文件派继,vim .swiftlint.yml
(2) 第二步:自定義規(guī)則:
-
disabled_rules
:禁用規(guī)則 -
opt_in_rules
:從默認(rèn)的可用規(guī)則集合中蒸走,禁用規(guī)則 -
whitelist_rules
:白名單規(guī)則仇奶,只有在這個(gè)列表的規(guī)則才會(huì)被激活,在這個(gè)列表激活的規(guī)則不能出現(xiàn)在disabled_rules
或者opt_in_rules
比驻。
自定義配置文件示例
disabled_rules: # 禁用規(guī)則
- colon
- comma
- control_statement
opt_in_rules: # 可選規(guī)則
- empty_count
- missing_docs
# 執(zhí)行這個(gè)命令可以查看所有規(guī)則: swiftlint rules
included: # 指定需要進(jìn)行風(fēng)格檢查的路徑
- Source
excluded: # 指定不需要進(jìn)行風(fēng)格檢查的路徑该溯,優(yōu)先于included
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
# 自定義某個(gè)規(guī)則
force_cast: warning # 隱式地
force_try:
severity: warning # 顯式地
# 有warning和error的規(guī)則,可以僅僅設(shè)置warning
# 隱式地
line_length: 110
# 使用一個(gè)數(shù)組隱式地設(shè)置
type_body_length:
- 300 # warning
- 400 # error
# 或者顯式地設(shè)置
file_length:
warning: 500
error: 1200
# 命名規(guī)則可以為min_length和max_length設(shè)置warnings或者errors
# 另外可以設(shè)置某些名字除外
type_name:
min_length: 4 # 只設(shè)置 warning
max_length: # 同時(shí)設(shè)置warning和error
warning: 40
error: 50
excluded: iPhone # 這些字符串除外
identifier_name:
min_length: # 只設(shè)置 min_length
error: 4 # 只設(shè)置 error
excluded: # 這些字符串除外
- id
- URL
- GlobalAPIKey
reporter: "xcode" # 指定報(bào)告類型 (xcode, json, csv, checkstyle, junit, html, emoji)
(3) 第三步:項(xiàng)目中實(shí)際使用
included:
- TDWCashLoan/Business/Me/Credit
excluded:
- Pods
disabled_rules:
- trailing_newline
- opening_brace
- empty_count
- comma
- colon
- force_cast
- type_name
- trailing_semicolon
- force_try
- function_body_length
- nesting
- variable_name
- operator_whitespace
- control_statement
- legacy_constant
- line_length
- return_arrow_whitespace
- trailing_whitespace
- closing_brace
- statement_position
- type_body_length
- todo
- legacy_constructor
- valid_docs
- missing_docs
- file_length
- leading_whitespace
(4) 第四步:swiftLint命令
autocorrect 自動(dòng)更正warnings和errors
help 查看幫助
lint 查看當(dāng)前文件夾的文件中的warnings和errors别惦,這是默認(rèn)命令
rules 查看所有規(guī)則
version 查看SwiftLint的版本
保險(xiǎn)起見狈茉,先備份代碼。先把所有想要檢查的規(guī)則放大disabled_rules
掸掸,然后每刪除一個(gè)規(guī)則氯庆,保存一下,xcode編譯一次(或者在終端執(zhí)行swiftlint
)扰付,一些規(guī)則可以自動(dòng)解決堤撵,到具體的目錄下執(zhí)行:swiftlint autocorrect
,如果不能自動(dòng)解決羽莺,那么需要手動(dòng)一個(gè)個(gè)改实昨,直到所有規(guī)則刪除完為止
更新SwiftLint
如果SwiftLint有新版本,在終端執(zhí)行brew upgrade swiftlint
盐固,然后再編譯一下荒给,看看項(xiàng)目有哪些代碼風(fēng)格問(wèn)題。