让你的代码更规范,Swiftlint的使用

SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 GitHub’s Swift 代码风格指南为基础。
SwiftLint Hook 了 Clang 和 SourceKit 从而能够使用 AST 来表示源代码文件的更多精确结果。

安装

swiftlint官方给出了几种安装方式,这边我使用Homebrew的方式进行安装,步骤如下:

  1. 安装Homebrew (如果没有的话)
  2. Terminal 执行 brew install swiftlint
  3. 在项目中添加一个新的 Run Script Phase :
if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

通过以上步骤就已经把Swiftlint安装到Mac,并集成在项目中了。

使用

使用的话没有什么说的,安装完成后Command + B编译,swiftlint就会对你项目中不规范的代码报出警告。

但是如果你项目中使用了其他第三方库的话,你又按照上面的做法来编译,那么你就有可能会一脸懵逼,Xcode瞬间给你999+ error

这时我们就需要修改Swfitlint的配置文件,也就是告诉swiftlint需要检查哪些源码,以及检查的规则。

配置

配置文件夹

  1. 在工程的根目录下新建一个.swiftlint.yml文件
  2. 在文件内写入规则:
included: # 执行 linting 时包含的路径。如果出现这个 `--path` 会被忽略。
- Source
excluded: # 执行 linting 时忽略的路径。 优先级比 `included` 更高。
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
disabled_rules: # 执行时排除掉的规则
- colon
- comma
- control_statement
opt_in_rules: # 一些规则仅仅是可选的
- empty_count
- missing_docs
# 可以通过执行如下指令来查找所有可用的规则:
# swiftlint rules

配置规则

官方还提供了自定义规则的方法,基于正则表达式

custom_rules:
pirates_beat_ninjas: # 规则标识符
name: "Pirates Beat Ninjas" # 规则名称,可选
regex: "([n,N]inja)" # 匹配的模式
match_kinds: # 需要匹配的语法类型,可选
- comment
- identifier
message: "Pirates are better than ninjas." # 提示信息,可选
severity: error # 提示的级别,可选
no_hiding_in_strings:
regex: "([n,N]inja)"
match_kinds: string

更多类容可以查看:Swfitlint 规则

小Tips

在确定源码被正常备份后使用swiftlint autocorrect指令可以对源代码进行自动修正

可以通过在一个源文件中定义一个如下格式的注释来关闭某个规则:
// swiftlint:disable <rule>
在该文件结束之前或者在定义如下格式的匹配注释之前,这条规则都会被禁用:
// swiftlint:enable <rule>

下面是我个人的配置文件分享:

included: # 检查的目录
excluded: # 忽略检查的目录,优先级比included高
- Carthage
- Pods
identifier_name:
min_length: # not possible to disable this partial rule, so set it to zero
warning: 0
error: 0
excluded:
- _addNotificationBlock(_:)
- _nsError
- _nsErrorDomain
- id
- pk
- to
file_length: 1000 #文件的行数
line_length: 150 # 每一行的字符数