iOS项目引入SwiftLint说明

平安喜乐

iOS项目中集成SwiftLint

SwiftLint源码-GitHub

1)在Mac上通过HomeBrew命令来安装

brew install swiftlint

2)在Xcode的Build Phase中新增一个Run Script Phase,添加如下脚本

export PATH=``"$PATH:/opt/homebrew/bin"
if which swiftlint > /dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from [https://github.com/realm/SwiftLint](https://github.com/realm/SwiftLint)"
fi

3)在Podfile中引入SwiftLint,之后执行命令pod install

pod 'SwiftLint'

SwiftLint的规则

SwiftLint v0.52版本目前已经支持超过200条规则,Swift社区也在不断的贡献更多的规则;

在终端中运行 swiftlint rules 来获取当前版本SwiftLint所支持的所有规则;

默认情况下,当代码触犯了相应规则时,程序编译后会给出警告或者报错,警告和报错的条件均可自定义;

一些常用的规则如下:

  • closure_body_length:闭包不应跨越太多行
  • closure_end_indentation:闭包前后缩进应相同
  • conditional_returns_on_newline:条件语句与结果不建议写在一行 ,
    例如:guard true else { return } ;if true { return "YES" } else { return "NO" } 会有 warning提示
  • discouraged_none_name:避免使用none 做变量名
  • expiring_todo:TODO和FIXME应该在其到期日之前解决
  • force_unwrapping:避免强制解包
  • unavailable_function:未实现的功能应标记为不可用
  • unused_import:import 的文件要被使用
  • weak_delegate:代理要设置为弱引用
  • file_length:文件长度
  • function_body_length:函数体长度限制 warning: 40, error: 100
  • function_parameter_count:函数参数个数 默认5 warning 8 error
  • shorthand_operator:使用+= , -=, *=, /= 代替 a = a + 1

自动修复SwiftLint冲突

SwiftLint中的一些规则是可以自动修正的,在终端运行 swiftlint --fix即可;

swiftlint --fix

或者,也可以讲自动修正的逻辑集成到Build Phase中,如:

export PATH="$PATH:/opt/homebrew/bin"
if which swiftlint > /dev/null; then
swiftlint --fix && swiftlint
else
echo "warning: SwiftLint not installed, download from [https://github.com/realm/SwiftLint](https://github.com/realm/SwiftLint)"
fi

SwiftLint的配置文件

项目中针对SwiftLint规则的配置都在.swiftlint.yml文件里,这个文件默认是隐藏的,可以通过 Shift + Command + .来显示;

.swiftlint.yml文件内部如下:

excluded:  # 不针对以下路径的文件进行检测
  - Test/Test/ThirdParty
 
included: # 检测以下路径的文件
  - Test
 
disabled_rules: # 以下规则不生效
  - line_length
  - todo
 
# rules that have both warning and error levels, can set just the warning level
line_length: 120  # 一行的字符长度不超过120个,否则会有warning
 
file_length:  # 文件行数超过500行会有warning,超过1200行会有error
  warning: 500
  error: 1200
 
opt_in_rules: # 禁止强解包
  - force_unwrapping
force_unwrapping:
  severity: error

由上面可知:
included:需要检测的目录
excluded:不需要检测的目录(优先级高于included)
disabled_rules:需要屏蔽掉的规则

同时也可以自定义规则在报错和警告时的条件。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容