SwiftLint
Enforce Swift style and conventions with static analysis. Lint entire projects, autocorrect fixable violations, manage rules, and integrate with Xcode and CI — all from the CLI.
Verify Installation
CODEBLOCK0
If not installed:
CODEBLOCK1
Or via Mint:
CODEBLOCK2
Or as a Swift Package Manager plugin (add to Package.swift):
CODEBLOCK3
Then run:
CODEBLOCK4
Basic Usage
Lint Current Directory
CODEBLOCK5
This recursively lints all .swift files from the current directory.
Lint a Specific Path
CODEBLOCK6
Lint Specific Files
CODEBLOCK7
Lint from Standard Input
CODEBLOCK8
Agent guidance: When a user says "check my code style" or "lint my Swift code," run swiftlint from the project root. If they point to a specific file or folder, use --path.
Autocorrect
SwiftLint can automatically fix certain violations.
Fix All Autocorrectable Violations
CODEBLOCK9
Fix a Specific Path
CODEBLOCK10
Fix a Specific File
CODEBLOCK11
Preview What Would Be Fixed (Dry Run)
Lint first to see violations, then fix:
CODEBLOCK12
Agent guidance: Always lint before autocorrecting so the user sees what will change. Some violations are not autocorrectable — report those separately after fixing.
Output Formats
Default (Human-Readable)
CODEBLOCK13
Output: INLINECODE4
JSON
CODEBLOCK14
CSV
CODEBLOCK15
Checkstyle (XML)
CODEBLOCK16
GitHub Actions
CODEBLOCK17
Xcode Summary (plist)
CODEBLOCK18
SonarQube
CODEBLOCK19
Markdown
CODEBLOCK20
Save to File
CODEBLOCK21
All Available Reporters
| Reporter | Format | Best For |
|---|
| INLINECODE5 | Xcode-compatible (default) | Local development |
| INLINECODE6 |
JSON array | Programmatic processing |
|
csv | CSV | Spreadsheet analysis |
|
checkstyle | XML | Jenkins, CI tools |
|
codeclimate | Code Climate JSON | Code Climate integration |
|
github-actions-logging | GitHub annotations | GitHub Actions CI |
|
sonarqube | SonarQube JSON | SonarQube integration |
|
markdown | Markdown table | PR comments |
|
emoji | Emoji-decorated | Fun terminal output |
|
html | HTML report | Browser viewing |
|
junit | JUnit XML | Test reporting tools |
|
xcode-summary | Plist | Xcode build summaries |
Agent guidance: Use --reporter json when you need to parse results programmatically. Use --reporter github-actions-logging on GitHub Actions to get inline annotations on PRs.
Rules
List All Rules
CODEBLOCK22
Search for a Specific Rule
CODEBLOCK23
Show Rule Details
CODEBLOCK24
Rule Identifiers Quick Reference
Rules fall into categories:
Enabled by Default (Common)
| Rule | What It Catches |
|---|
| INLINECODE19 | Lines exceeding max length (default 120 warning, 200 error) |
| INLINECODE20 |
Whitespace at end of lines |
|
trailing_newline | Missing or extra trailing newlines |
|
opening_brace | Opening brace placement |
|
closing_brace | Closing brace placement |
|
colon | Colon spacing (e.g.,
let x : Int →
let x: Int) |
|
comma | Comma spacing |
|
force_cast | Use of
as! |
|
force_try | Use of
try! |
|
force_unwrapping | Use of
! on optionals (opt-in) |
|
type_body_length | Type bodies exceeding max lines |
|
function_body_length | Function bodies exceeding max lines |
|
file_length | Files exceeding max lines |
|
cyclomatic_complexity | High cyclomatic complexity |
|
nesting | Deep nesting levels |
|
identifier_name | Naming convention violations |
|
type_name | Type naming convention violations |
|
unused_import | Unused import statements (opt-in) |
|
unused_declaration | Unused declarations (opt-in) |
|
vertical_whitespace | Excessive blank lines |
|
todo | TODO/FIXME comments as warnings |
|
mark | Improper MARK comment format |
|
void_return | Explicit
-> Void instead of
-> () |
|
syntactic_sugar | Prefer
[Int] over
Array<Int> |
|
redundant_optional_initialization |
var x: Int? = nil (nil is default) |
|
redundant_string_enum_value | Enum case name matches raw value |
Opt-In (Must Be Explicitly Enabled)
| Rule | What It Catches |
|---|
| INLINECODE55 | Missing explicit type annotations |
| INLINECODE56 |
Missing documentation comments |
|
multiline_arguments | Multiline function call formatting |
|
multiline_parameters | Multiline function param formatting |
|
vertical_parameter_alignment | Parameter alignment in declarations |
|
sorted_imports | Unsorted import statements |
|
file_header | Missing or incorrect file headers |
|
accessibility_label_for_image | Images without accessibility labels |
|
accessibility_trait_for_button | Buttons without accessibility traits |
|
strict_fileprivate | Prefer
private over
fileprivate |
|
prohibited_interface_builder | Storyboard/XIB usage |
|
no_magic_numbers | Magic numbers in code |
|
prefer_self_in_static_references |
Self over explicit type name in static context |
|
balanced_xctest_lifecycle | setUp without tearDown |
|
test_case_accessibility | Test methods not marked correctly |
Agent guidance: When setting up SwiftLint for a new project, start with defaults and only add opt-in rules the user specifically requests. Don't overwhelm with every possible rule.
Configuration (.swiftlint.yml)
SwiftLint reads .swiftlint.yml from the current directory (or parent directories).
Generate a Default Config
There's no built-in generator, but here's a minimal config:
CODEBLOCK25
Using a Config from a Custom Path
CODEBLOCK26
Multiple Configs (Child Config)
CODEBLOCK27
Parent Config (Extend from Another)
CODEBLOCK28
Remote Config
CODEBLOCK29
Agent guidance: When a project already has .swiftlint.yml, always read it before suggesting changes. Modify the existing config rather than creating a new one.
Inline Rule Management
Disable a Rule for a Line
CODEBLOCK30
Disable a Rule for a Block
CODEBLOCK31
Disable All Rules for a Block
CODEBLOCK32
Disable for Next Line Only
CODEBLOCK33
Disable for Previous Line
CODEBLOCK34
Agent guidance: Prefer targeted disables (disable:this, disable:next) over broad block disables. Never suggest disable all unless the user is dealing with generated code or legacy code they explicitly don't want to lint.
Xcode Integration
Build Phase Script
Add a Run Script Phase in Xcode (Build Phases):
CODEBLOCK35
Build Phase with Autocorrect
CODEBLOCK36
Swift Package Plugin (Xcode 15+)
If SwiftLint is added as a package dependency:
CODEBLOCK37
Or in Xcode: right-click the project → "SwiftLintBuildToolPlugin".
Agent guidance: For modern projects (Xcode 15+), prefer the SPM plugin over a build phase script — it pins the SwiftLint version to the project and doesn't require a local install.
CI Integration
GitHub Actions
CODEBLOCK38
With only changed files:
CODEBLOCK39
Bitrise
CODEBLOCK40
Jenkins (Checkstyle)
CODEBLOCK41
Then use the Checkstyle plugin to parse swiftlint-checkstyle.xml.
Analyzing Results
Count Violations by Rule
CODEBLOCK42
Show Only Errors (Not Warnings)
CODEBLOCK43
Strict Mode (Warnings Become Errors)
CODEBLOCK44
This makes SwiftLint return a non-zero exit code for any violation (not just errors).
Quiet Mode (Errors Only in Output)
CODEBLOCK45
Suppresses warnings from output, only shows errors.
Enable/Disable Specific Rules via CLI
CODEBLOCK46
Custom Rules
Define custom regex-based rules in .swiftlint.yml:
CODEBLOCK47
Match Kinds
| Kind | What It Matches |
|---|
| INLINECODE80 | Variable/function names |
| INLINECODE81 |
String literals |
|
comment | Comments |
|
keyword | Swift keywords |
|
typeidentifier | Type names |
|
number | Numeric literals |
|
parameter | Function parameters |
|
argument | Function arguments |
Agent guidance: Custom rules are powerful but regex-based — they can produce false positives. Always test custom rules on the codebase before suggesting them as permanent additions.
Common Flags Reference
| Flag | Purpose |
|---|
| INLINECODE88 | Lint specific file or directory |
| INLINECODE89 |
Use custom config file |
|
--reporter <name> | Output format (json, csv, etc.) |
|
--strict | Treat warnings as errors |
|
--quiet | Only show errors in output |
|
--fix | Autocorrect fixable violations |
|
--enable-rules <rules> | Enable specific rules (comma-separated) |
|
--disable-rules <rules> | Disable specific rules (comma-separated) |
|
--use-stdin | Read Swift from stdin |
|
--force-exclude | Exclude files even if explicitly passed |
|
--cache-path <path> | Custom cache directory |
|
--no-cache | Disable caching |
|
--use-alternative-excluding | Use alternative file-excluding method |
|
--in-process-sourcekit | Use in-process SourceKit |
|
--compiler-log-path | Path to xcodebuild log for analyzer rules |
|
--progress | Show progress bar |
Common Workflows
Set Up SwiftLint for a New Project
CODEBLOCK48
Fix All Issues Before a PR
CODEBLOCK49
Lint Only Changed Files (vs. main)
CODEBLOCK50
Compare Violation Counts Between Branches
CODEBLOCK51
Troubleshooting
Common Errors
| Error | Solution |
|---|
| INLINECODE104 | Check included paths in config or run from project root |
| INLINECODE106 |
Validate YAML syntax in
.swiftlint.yml |
|
SourceKit not found | Run
sudo xcode-select -s /Applications/Xcode.app |
|
Rule not found | Check rule name with
swiftlint rules, may be opt-in |
|
Slow linting | Add
excluded paths for Pods/DerivedData, use
--cache-path |
Performance Tips
- - Always exclude
Pods/, DerivedData/, .build/, and Packages/ in config - Use
--cache-path to persist cache across CI runs - Lint only changed files on CI instead of the entire project
- Use
--no-cache only when debugging unexpected results
Notes
Agent Tips
When a user asks to "clean up" or "fix style" in Swift code, run swiftlint --fix first, then swiftlint lint to report remaining issues.
Before adding SwiftLint to an existing project, run swiftlint lint --reporter json to assess the violation count. If there are hundreds of violations, suggest a phased approach: fix autocorrectable ones first, then tackle the rest by category.
Always check for an existing .swiftlint.yml before creating one. Read it to understand the team's style preferences.
For projects targeting accessibility (which should be all of them), suggest enabling accessibility_label_for_image and accessibility_trait_for_button opt-in rules.
When the user's project uses SwiftUI, suggest a custom rule to catch hardcoded strings in Text() views — all user-facing strings should use String(localized:) for localization support.
The --strict flag is essential for CI — without it, SwiftLint exits 0 even with warnings, which means your CI pipeline won't catch style regressions.
SwiftLint
通过静态分析强制执行 Swift 风格和约定。对整个项目进行代码检查,自动修正可修复的违规,管理规则,并与 Xcode 和 CI 集成——全部通过命令行完成。
验证安装
bash
swiftlint version
如果未安装:
bash
brew install swiftlint
或通过 Mint:
bash
mint install realm/SwiftLint
或作为 Swift Package Manager 插件(添加到 Package.swift):
swift
.package(url: https://github.com/realm/SwiftLint.git, from: 0.57.0)
然后运行:
bash
swift package plugin swiftlint
基本用法
检查当前目录
bash
swiftlint
这将递归检查当前目录中的所有 .swift 文件。
检查特定路径
bash
swiftlint lint --path Sources/
检查特定文件
bash
swiftlint lint --path Sources/App/ViewModel.swift
从标准输入检查
bash
cat MyFile.swift | swiftlint lint --use-stdin --quiet
Agent 指导: 当用户说检查我的代码风格或检查我的 Swift 代码时,从项目根目录运行 swiftlint。如果他们指向特定文件或文件夹,使用 --path。
自动修正
SwiftLint 可以自动修复某些违规。
修复所有可自动修正的违规
bash
swiftlint --fix
修复特定路径
bash
swiftlint --fix --path Sources/
修复特定文件
bash
swiftlint --fix --path Sources/App/ViewModel.swift
预览将要修复的内容(试运行)
先检查以查看违规,然后修复:
bash
swiftlint lint --path Sources/ && swiftlint --fix --path Sources/
Agent 指导: 在自动修正之前始终先进行检查,以便用户看到将要更改的内容。某些违规无法自动修正——在修复后单独报告这些违规。
输出格式
默认(人类可读)
bash
swiftlint
输出:Sources/App.swift:12:1: warning: Line Length Violation: ...
JSON
bash
swiftlint lint --reporter json
CSV
bash
swiftlint lint --reporter csv
Checkstyle(XML)
bash
swiftlint lint --reporter checkstyle
GitHub Actions
bash
swiftlint lint --reporter github-actions-logging
Xcode 摘要(plist)
bash
swiftlint lint --reporter xcode-summary
SonarQube
bash
swiftlint lint --reporter sonarqube
Markdown
bash
swiftlint lint --reporter markdown
保存到文件
bash
swiftlint lint --reporter json > swiftlint-results.json
所有可用的报告器
| 报告器 | 格式 | 最佳用途 |
|---|
| xcode | Xcode 兼容(默认) | 本地开发 |
| json |
JSON 数组 | 程序化处理 |
| csv | CSV | 电子表格分析 |
| checkstyle | XML | Jenkins、CI 工具 |
| codeclimate | Code Climate JSON | Code Climate 集成 |
| github-actions-logging | GitHub 注释 | GitHub Actions CI |
| sonarqube | SonarQube JSON | SonarQube 集成 |
| markdown | Markdown 表格 | PR 评论 |
| emoji | 表情符号装饰 | 有趣的终端输出 |
| html | HTML 报告 | 浏览器查看 |
| junit | JUnit XML | 测试报告工具 |
| xcode-summary | Plist | Xcode 构建摘要 |
Agent 指导: 当需要以编程方式解析结果时使用 --reporter json。在 GitHub Actions 上使用 --reporter github-actions-logging 以在 PR 上获得内联注释。
规则
列出所有规则
bash
swiftlint rules
搜索特定规则
bash
swiftlint rules | grep force_cast
显示规则详情
bash
swiftlint rules force_cast
规则标识符快速参考
规则分为以下几类:
默认启用(常见)
| 规则 | 捕获内容 |
|---|
| linelength | 超过最大长度的行(默认警告 120,错误 200) |
| trailingwhitespace |
行尾空白 |
| trailing_newline | 缺少或多余的行尾换行符 |
| opening_brace | 左大括号位置 |
| closing_brace | 右大括号位置 |
| colon | 冒号间距(例如 let x : Int → let x: Int) |
| comma | 逗号间距 |
| force_cast | 使用 as! |
| force_try | 使用 try! |
| force_unwrapping | 对可选类型使用 !(可选加入) |
| type
bodylength | 类型体超过最大行数 |
| function
bodylength | 函数体超过最大行数 |
| file_length | 文件超过最大行数 |
| cyclomatic_complexity | 高圈复杂度 |
| nesting | 深层嵌套级别 |
| identifier_name | 命名约定违规 |
| type_name | 类型命名约定违规 |
| unused_import | 未使用的导入语句(可选加入) |
| unused_declaration | 未使用的声明(可选加入) |
| vertical_whitespace | 过多的空行 |
| todo | TODO/FIXME 注释作为警告 |
| mark | 不正确的 MARK 注释格式 |
| void_return | 显式 -> Void 而不是 -> () |
| syntactic_sugar | 优先使用 [Int] 而不是 Array
|
| redundantoptionalinitialization | var x: Int? = nil(nil 是默认值) |
| redundantstringenum_value | 枚举 case 名称匹配原始值 |
可选加入(必须显式启用)
| 规则 | 捕获内容 |
|---|
| explicittypeinterface | 缺少显式类型注解 |
| missing_docs |
缺少文档注释 |
| multiline_arguments | 多行函数调用格式 |
| multiline_parameters | 多行函数参数格式 |
| verticalparameteralignment | 声明中的参数对齐 |
| sorted_imports | 未排序的导入语句 |
| file_header | 缺少或不正确的文件头 |
| accessibilitylabelfor_image | 没有无障碍标签的图像 |
| accessibilitytraitfor_button | 没有无障碍特性的按钮 |
| strict_fileprivate | 优先使用 private 而不是 fileprivate |
| prohibitedinterfacebuilder | Storyboard/XIB 使用 |
| nomagicnumbers | 代码中的魔法数字 |
| preferselfinstaticreferences | 在静态上下文中使用 Self 而不是显式类型名 |
| balancedxctestlifecycle | 有 setUp 但没有 tearDown |
| testcaseaccessibility | 测试方法未正确标记 |
Agent 指导: 为新项目设置 SwiftLint 时,从默认规则开始,只添加用户特别请求的可选加入规则。不要用所有可能的规则让用户不知所措。
配置(.swiftlint.yml)
SwiftLint 从当前目录(或父目录)读取 .swiftlint.yml。
生成默认配置
没有内置的生成器,但这里有一个最小配置:
yaml
.swiftlint.yml
要包含的路径(默认:所有 Swift 文件)
included:
- Sources
- Tests
要排除的路径
excluded:
- Pods
- DerivedData
- .build
- Packages
禁用特定规则
disabled_rules:
- todo
- trailing_whitespace
启用可选加入规则
optinrules:
- sorted_imports
- unused_import
- missing_docs
配置特定规则
line_length:
warning: 120
error: 200
ignores_comments: true
ignores_urls: true
typebodylength:
warning: 300
error: 500
file_length:
warning: 500
error: 1000
functionbodylength:
warning: 50
error: 100