swiftlint
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwiftLint
SwiftLint
SwiftLint enforces Swift style and conventions by linting source files against a configurable rule set. It is the most widely adopted Swift linter. This skill covers setup, configuration, rule selection, suppression, CI integration, and rollout strategy.
SwiftLint is a style enforcement tool, not a style guide. For underlying Swift naming and design conventions, see . For architecture patterns, see .
swift-api-design-guidelinesswift-architectureSwiftLint通过对照可配置的规则集检查源文件,来强制执行Swift代码风格和规范。它是应用最广泛的Swift代码检查工具。本技能涵盖设置、配置、规则选择、抑制、CI集成以及推广策略。
SwiftLint是一款代码风格强制执行工具,而非风格指南。如需了解底层Swift命名与设计规范,请参考。如需架构模式相关内容,请参考。
swift-api-design-guidelinesswift-architectureContents
目录
Recommended Setup
推荐设置
Default: build tool plugin via .
SimplyDanny/SwiftLintPluginsAdd the plugin package to or via Xcode's package dependencies:
Package.swiftswift
// Package.swift
dependencies: [
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<reviewed-version>")
]For SwiftPM targets, apply the plugin:
swift
.target(
name: "MyApp",
plugins: [.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")]
)For Xcode projects without a , add the package dependency in the project settings, then enable the plugin under the target's Build Phases or the package's plugin trust dialog.
Package.swiftThe build tool plugin runs SwiftLint automatically on every build. No run script required.
First build: Xcode prompts to trust the plugin. Select "Trust & Enable All" for the SwiftLintPlugins package.
For alternatives (run scripts, command plugin, Homebrew CLI), see references/plugins-run-scripts-and-integrations.md.
默认方案:通过使用构建工具插件。
SimplyDanny/SwiftLintPlugins将插件包添加到或通过Xcode的包依赖管理添加:
Package.swiftswift
// Package.swift
dependencies: [
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<reviewed-version>")
]对于SwiftPM目标,应用该插件:
swift
.target(
name: "MyApp",
plugins: [.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")]
)对于没有的Xcode项目,在项目设置中添加包依赖,然后在目标的Build Phases或包的插件信任对话框中启用该插件。
Package.swift构建工具插件会在每次构建时自动运行SwiftLint,无需额外配置运行脚本。
首次构建:Xcode会提示信任插件。为SwiftLintPlugins包选择“Trust & Enable All”。
如需了解替代方案(运行脚本、命令插件、Homebrew CLI),请查看references/plugins-run-scripts-and-integrations.md。
Configuration
配置
Create at the project root. SwiftLint discovers this file by walking up from each source file's directory.
.swiftlint.ymlyaml
undefined在项目根目录创建文件。SwiftLint会从每个源文件的目录向上遍历,自动发现该文件。
.swiftlint.ymlyaml
undefined.swiftlint.yml — conservative starter config
.swiftlint.yml — 保守的初始配置
disabled_rules:
- trailing_whitespace
- todo
opt_in_rules:
- empty_count
- closure_spacing
- force_unwrapping
- sorted_imports
- vertical_whitespace_opening_braces
- private_swiftui_state
- unhandled_throwing_task
- accessibility_label_for_image
included:
- Sources
- Tests
excluded:
- .build
- DerivedData
- "**/.build"
- "**/Generated"
line_length:
warning: 140
error: 200
type_body_length:
warning: 300
error: 500
file_length:
warning: 500
error: 1000
Key configuration options:
| Key | Purpose |
|-----|---------|
| `disabled_rules` | Turn off default-enabled rules |
| `opt_in_rules` | Turn on rules not enabled by default |
| `only_rules` | Use _only_ the listed rules (mutually exclusive with `disabled_rules`/`opt_in_rules`) |
| `analyzer_rules` | Rules requiring compiler logs (run via `swiftlint analyze`) |
| `baseline` | Path to an existing baseline file used to suppress known violations |
| `write_baseline` | Path where SwiftLint should write a new baseline file |
| `included` | Paths to lint (default: current directory) |
| `excluded` | Paths to skip |
| `strict` | Elevate all warnings to errors |
| `lenient` | Downgrade all errors to warnings |
| `allow_zero_lintable_files` | Suppress the error when no Swift files are found |
| `reporter` | Output format: `xcode` (default), `json`, `checkstyle`, `sarif`, `csv`, `emoji`, etc. |
For full configuration details including severity tuning, environment-variable interpolation, and nested/remote configs, see [references/adoption-and-configuration.md](references/adoption-and-configuration.md).disabled_rules:
- trailing_whitespace
- todo
opt_in_rules:
- empty_count
- closure_spacing
- force_unwrapping
- sorted_imports
- vertical_whitespace_opening_braces
- private_swiftui_state
- unhandled_throwing_task
- accessibility_label_for_image
included:
- Sources
- Tests
excluded:
- .build
- DerivedData
- "**/.build"
- "**/Generated"
line_length:
warning: 140
error: 200
type_body_length:
warning: 300
error: 1000
file_length:
warning: 500
error: 1000
关键配置选项:
| 键 | 用途 |
|-----|---------|
| `disabled_rules` | 关闭默认启用的规则 |
| `opt_in_rules` | 启用默认未开启的规则 |
| `only_rules` | 仅使用列出的规则(与`disabled_rules`/`opt_in_rules`互斥) |
| `analyzer_rules` | 需要编译器日志的规则(通过`swiftlint analyze`运行) |
| `baseline` | 用于抑制已知违规的现有基线文件路径 |
| `write_baseline` | SwiftLint写入新基线文件的路径 |
| `included` | 需要检查的路径(默认:当前目录) |
| `excluded` | 需要跳过的路径 |
| `strict` | 将所有警告升级为错误 |
| `lenient` | 将所有错误降级为警告 |
| `allow_zero_lintable_files` | 当未找到Swift文件时抑制错误提示 |
| `reporter` | 输出格式:`xcode`(默认)、`json`、`checkstyle`、`sarif`、`csv`、`emoji`等 |
如需完整配置细节,包括严重程度调整、环境变量插值以及嵌套/远程配置,请查看[references/adoption-and-configuration.md](references/adoption-and-configuration.md)。Rule Selection Strategy
规则选择策略
SwiftLint ships with three rule categories:
- Default rules — enabled automatically, cover widely accepted conventions
- Opt-in rules — disabled by default, enable selectively via
opt_in_rules - Analyzer rules — require compiler logs, enabled via
analyzer_rules
Browse the full categorized list at https://realm.github.io/SwiftLint/rule-directory.html.
Recommended approach for new projects:
- Start with defaults. Run to see which rules are enabled.
swiftlint rules - Disable rules that conflict with your team's established conventions.
- Add opt-in rules one at a time. Review violations before committing each addition.
- Do not use unless you have a specific reason to start from zero.
only_rules
Recommended approach for existing codebases:
- Start with the default rule set.
- Create a baseline (see Baselines) to suppress all existing violations.
- Enforce zero new violations in CI.
- Burn down baseline violations incrementally.
Do not transcribe or memorize the rule directory. Look up rule identifiers and configuration options at the official rule directory when needed.
SwiftLint包含三类规则:
- 默认规则 — 自动启用,涵盖广泛认可的规范
- 可选规则 — 默认禁用,需通过选择性启用
opt_in_rules - 分析器规则 — 需要编译器日志,通过启用
analyzer_rules
可在https://realm.github.io/SwiftLint/rule-directory.html浏览完整的分类规则列表。
新项目推荐方案:
- 从默认规则开始。运行查看已启用的规则。
swiftlint rules - 禁用与团队既定规范冲突的规则。
- 逐个添加可选规则。在提交每个新增规则前,先审核违规情况。
- 除非有特殊理由需要从零开始,否则不要使用。
only_rules
现有代码库推荐方案:
- 从默认规则集开始。
- 创建基线(查看基线)以抑制所有现有违规。
- 在CI中强制要求零新增违规。
- 逐步修复基线中的违规内容。
无需抄写或记忆规则目录。需要时,可在官方规则目录中查找规则标识符和配置选项。
Suppressions
规则抑制
Suppress SwiftLint for specific lines when a rule produces a false positive or when the violation is intentional and reviewed.
swift
// swiftlint:disable:next force_cast
let view = object as! UIView
let legacy = try! JSONDecoder().decode(T.self, from: data) // swiftlint:disable:this force_try
// swiftlint:disable:previous large_tupleDisable for a region:
swift
// swiftlint:disable cyclomatic_complexity
func complexRouter(...) { ... }
// swiftlint:enable cyclomatic_complexityDisable all rules (use sparingly):
swift
// swiftlint:disable all
// ... generated or legacy code ...
// swiftlint:enable allPolicy:
- Prefer targeted single-rule suppressions over .
all - Always re-enable after the region ends.
- For generated code, prefer paths in
excludedover inline suppressions..swiftlint.yml - For test targets with different tolerance, use a child configuration (see Multiple Configurations).
For full suppression syntax, see references/rules-suppressions-and-baselines.md.
当规则产生误报,或违规是经过审核的有意操作时,可针对特定行抑制SwiftLint检查。
swift
// swiftlint:disable:next force_cast
let view = object as! UIView
let legacy = try! JSONDecoder().decode(T.self, from: data) // swiftlint:disable:this force_try
// swiftlint:disable:previous large_tuple针对代码块禁用规则:
swift
// swiftlint:disable cyclomatic_complexity
func complexRouter(...) { ... }
// swiftlint:enable cyclomatic_complexity禁用所有规则(谨慎使用):
swift
// swiftlint:disable all
// ... 自动生成或遗留代码 ...
// swiftlint:enable all规范:
- 优先使用针对单一规则的抑制,而非。
all - 代码块结束后务必重新启用规则。
- 对于自动生成的代码,优先在中配置
.swiftlint.yml路径,而非行内抑制。excluded - 对于容错性不同的测试目标,使用子配置(查看多配置)。
如需完整抑制语法,请查看references/rules-suppressions-and-baselines.md。
Baselines
基线
Baselines let you adopt SwiftLint in an existing codebase without fixing every legacy violation first.
Create a baseline:
sh
swiftlint --write-baseline .swiftlint.baselineThis records all current violations. Future runs compare against this baseline and only report new violations.
Use the baseline:
sh
swiftlint --baseline .swiftlint.baselineIn CI, pass so only new violations fail the build. Burn down the baseline over time by fixing legacy violations and regenerating.
--baselineFor baseline workflows and rollout strategy, see references/rules-suppressions-and-baselines.md.
基线功能允许你在现有代码库中引入SwiftLint,而无需先修复所有遗留违规。
创建基线:
sh
swiftlint --write-baseline .swiftlint.baseline该命令会记录所有当前违规。后续运行时会与该基线对比,仅报告新增违规。
使用基线:
sh
swiftlint --baseline .swiftlint.baseline在CI中,传入参数,这样只有新增违规会导致构建失败。通过修复遗留违规并重新生成基线,逐步减少基线中的违规内容。
--baseline如需基线工作流和推广策略,请查看references/rules-suppressions-and-baselines.md。
Autocorrect
自动修正
SwiftLint can fix some violations automatically:
sh
swiftlint --fixSwiftLint可自动修复部分违规:
sh
swiftlint --fixor the legacy alias:
或旧版别名:
swiftlint --autocorrect
**Warnings:**
- **Never run `--fix` as a pre-compile build phase.** Auto-fixes modify source files. If run automatically on every build, this creates an unpredictable edit-build loop and can mask real issues.
- Run `--fix` manually or in a dedicated CI step, then review the diff.
- Not all rules support autocorrect. Check `swiftlint rules` — the "Correctable" column shows which rules can auto-fix.
- Always commit or stash before running `--fix`.swiftlint --autocorrect
**注意事项:**
- **切勿将`--fix`作为预编译构建阶段运行**。自动修正会修改源文件。如果每次构建自动运行,会造成不可预测的编辑-构建循环,并可能掩盖真实问题。
- 手动运行`--fix`,或在专门的CI步骤中运行,然后审核差异。
- 并非所有规则都支持自动修正。运行`swiftlint rules`查看——“Correctable”列显示哪些规则可自动修复。
- 运行`--fix`前,务必提交或暂存代码。CI Integration
CI集成
CI is the primary enforcement surface. A CI check ensures no one merges code that increases the violation count.
Recommended CI pattern:
yaml
undefinedCI是主要的强制执行环节。CI检查可确保无人提交增加违规数量的代码。
推荐CI模式:
yaml
undefinedGitHub Actions example
GitHub Actions示例
- name: Lint run: | brew install swiftlint swiftlint --strict --reporter sarif > swiftlint.sarif
Key CI options:
| Flag | Effect |
|------|--------|
| `--strict` | Exits non-zero on warnings (not just errors) |
| `--reporter sarif` | GitHub Advanced Security compatible output |
| `--reporter json` | Machine-readable output |
| `--reporter checkstyle` | Jenkins/SonarQube compatible |
| `--baseline .swiftlint.baseline` | Only fail on new violations |
For SARIF upload to GitHub code scanning, add `github/codeql-action/upload-sarif` after the lint step.
For full CI recipes and reporter details, see [references/plugins-run-scripts-and-integrations.md](references/plugins-run-scripts-and-integrations.md).- name: Lint run: | brew install swiftlint swiftlint --strict --reporter sarif > swiftlint.sarif
关键CI选项:
| 参数 | 作用 |
|------|--------|
| `--strict` | 遇到警告(不仅是错误)时返回非零退出码 |
| `--reporter sarif` | 生成兼容GitHub Advanced Security的输出 |
| `--reporter json` | 生成机器可读的输出 |
| `--reporter checkstyle` | 生成兼容Jenkins/SonarQube的输出 |
| `--baseline .swiftlint.baseline` | 仅在出现新增违规时构建失败 |
如需将SARIF上传到GitHub代码扫描,在lint步骤后添加`github/codeql-action/upload-sarif`。
如需完整CI方案和报告器细节,请查看[references/plugins-run-scripts-and-integrations.md](references/plugins-run-scripts-and-integrations.md)。Integration Decision Tree
集成决策树
Choose how to run SwiftLint based on project shape:
| Scenario | Recommended integration |
|---|---|
SwiftPM package or Xcode project with | Build tool plugin via |
SwiftPM project needing CLI flags ( | Command plugin: |
| Xcode project without SwiftPM, team uses Homebrew | Run script build phase |
| CI/CD pipeline | Homebrew or Docker install, run |
| Pre-commit hook | Homebrew install + |
The build tool plugin is preferred for local development because it requires no PATH configuration, pins the SwiftLint version via package resolution, and runs automatically on build.
For detailed setup instructions for each integration, see references/plugins-run-scripts-and-integrations.md.
根据项目类型选择SwiftLint的运行方式:
| 场景 | 推荐集成方式 |
|---|---|
SwiftPM包或带有 | 通过 |
需要CLI参数( | 命令插件: |
| 无SwiftPM的Xcode项目,团队使用Homebrew | 运行脚本构建阶段 |
| CI/CD流水线 | 通过Homebrew或Docker安装,直接运行 |
| 提交前钩子 | Homebrew安装 + |
构建工具插件是本地开发的首选方案,因为它无需配置PATH,通过包解析固定SwiftLint版本,并在构建时自动运行。
如需每种集成方式的详细设置说明,请查看references/plugins-run-scripts-and-integrations.md。
Multiple Configurations
多配置
SwiftLint supports layered configuration files. A in a subdirectory inherits from and overrides the parent config.
.swiftlint.ymlCommon patterns:
- Relaxed test config: place a in
.swiftlint.ymlthat disablesTests/and raisesforce_unwrappingfile_length - Strict module config: place a stricter in a shared module directory
.swiftlint.yml - Remote config: use with an HTTPS URL to pull a shared team config (caching supported)
parent_config
yaml
undefinedSwiftLint支持分层配置文件。子目录中的会继承并覆盖父配置。
.swiftlint.yml常见模式:
- 宽松测试配置:在目录下放置
Tests/,禁用.swiftlint.yml并提高force_unwrapping阈值file_length - 严格模块配置:在共享模块目录下放置更严格的
.swiftlint.yml - 远程配置:使用搭配HTTPS URL拉取团队共享配置(支持缓存)
parent_config
yaml
undefinedTests/.swiftlint.yml — child config
Tests/.swiftlint.yml — 子配置
disabled_rules:
- force_unwrapping
- force_try
file_length:
warning: 800
You can also pass multiple configs on the CLI:
```sh
swiftlint --config .swiftlint.yml --config .swiftlint-extra.ymlLater configs override earlier ones for overlapping keys.
For nested config resolution, remote configs, and CLI multi-config details, see references/adoption-and-configuration.md.
disabled_rules:
- force_unwrapping
- force_try
file_length:
warning: 800
你也可以在CLI中传入多个配置:
```sh
swiftlint --config .swiftlint.yml --config .swiftlint-extra.yml后续配置会覆盖先前配置中的重叠键值。
如需嵌套配置解析、远程配置和CLI多配置细节,请查看references/adoption-and-configuration.md。
Common Mistakes
常见错误
-
Runningin a build phase. Auto-fixing on every build creates unpredictable source modifications. Run
--fixmanually.--fix -
Usingwithout understanding the implication. This disables all rules except those listed. Most teams should use
only_rules+disabled_rulesinstead.opt_in_rules -
Suppressing withand forgetting to re-enable. This silently disables all linting for the rest of the file.
// swiftlint:disable all -
Not pinning the SwiftLint version. Different versions have different default rules. Use the build tool plugin (version pinned via SPM) or pin in your/ CI config.
Brewfile -
Excluding too broadly. Excludingentirely means test code gets no linting. Use a child config with relaxed rules instead.
Tests/ -
Ignoring the toolchain mismatch. SwiftLint must be built with (or compatible with) the same Swift toolchain used to compile your project. Mismatches cause parsing errors. See references/plugins-run-scripts-and-integrations.md for multi-toolchain guidance.
-
Adopting too many opt-in rules at once in a large codebase. This creates an overwhelming number of violations. Add rules incrementally and use baselines.
-
Not configuringpaths. Without
included, SwiftLint scans the working directory recursively, which may pick up vendored or generated code.included
-
在构建阶段运行。每次构建自动运行自动修正会造成不可预测的源文件修改。请手动运行
--fix。--fix -
未了解影响就使用。该选项会禁用所有未列出的规则。大多数团队应使用
only_rules+disabled_rules替代。opt_in_rules -
使用后忘记重新启用。这会静默禁用文件剩余部分的所有检查。
// swiftlint:disable all -
未固定SwiftLint版本。不同版本的默认规则不同。使用构建工具插件(通过SPM固定版本)或在/CI配置中固定版本。
Brewfile -
过度排除路径。完全排除意味着测试代码不会被检查。应使用子配置设置宽松规则,而非直接排除。
Tests/ -
忽略工具链不匹配。SwiftLint必须与编译项目所用的Swift工具链兼容(或使用同一工具链构建)。不匹配会导致解析错误。如需多工具链指导,请查看references/plugins-run-scripts-and-integrations.md。
-
在大型代码库中一次性启用过多可选规则。这会导致大量违规,难以处理。应逐步添加规则并使用基线。
-
未配置路径。如果没有
included配置,SwiftLint会递归扫描工作目录,可能会检查到第三方依赖或自动生成的代码。included
Review Checklist
审核检查清单
- exists at the project root with explicit
.swiftlint.yml/includedpathsexcluded - SwiftLint version is pinned (via SPM plugin resolution, Brewfile, or CI config)
- Build tool plugin is enabled for each target that should be linted
- CI runs (or with
swiftlint --strictfor incremental adoption)--baseline - No /
--fixin build phases--autocorrect - Inline suppressions target specific rules, not
all - Inline suppressions include a comment explaining why
- Test targets have appropriate config (relaxed rules via child config, not excluded entirely)
- Autocorrect changes are reviewed in a separate commit
- New opt-in rules are added one at a time with team consensus
- 项目根目录存在,并明确配置
.swiftlint.yml/included路径excluded - SwiftLint版本已固定(通过SPM插件解析、Brewfile或CI配置)
- 需要检查的每个目标都已启用构建工具插件
- CI运行(或针对增量引入使用
swiftlint --strict)--baseline - 构建阶段未配置/
--fix--autocorrect - 行内抑制针对特定规则,而非
all - 行内抑制包含注释说明原因
- 测试目标有合适的配置(通过子配置设置宽松规则,而非完全排除)
- 自动修正的变更在单独的提交中审核
- 新增可选规则逐个添加,并获得团队共识
References
参考资料
- references/adoption-and-configuration.md — Installation paths, deep dive, severity tuning, environment variables, nested/remote configs, rollout strategy
.swiftlint.yml - references/plugins-run-scripts-and-integrations.md — Build tool plugin, command plugin, run scripts, CI recipes, multi-toolchain guidance, VS Code, Fastlane, Docker, pre-commit
- references/rules-suppressions-and-baselines.md — Default vs opt-in vs analyzer rules, suppression syntax, baseline workflows, false-positive handling
- references/rule-reference.md — Bundled exhaustive rule index for local lookup; verify current details with or the official rule directory
swiftlint rules - references/custom-rules-and-analyze.md — Regex custom rules, Swift custom rules (brief), , compiler-log workflow
swiftlint analyze - SwiftLint documentation — Official docs
- SwiftLint rule directory — Full categorized rule list
- SimplyDanny/SwiftLintPlugins — Recommended plugin package
- references/adoption-and-configuration.md — 安装路径、深度解析、严重程度调整、环境变量、嵌套/远程配置、推广策略
.swiftlint.yml - references/plugins-run-scripts-and-integrations.md — 构建工具插件、命令插件、运行脚本、CI方案、多工具链指导、VS Code、Fastlane、Docker、提交前钩子
- references/rules-suppressions-and-baselines.md — 默认/可选/分析器规则、抑制语法、基线工作流、误报处理
- references/rule-reference.md — 完整内置规则索引,供本地查阅;可通过或官方规则目录验证最新细节
swiftlint rules - references/custom-rules-and-analyze.md — 正则自定义规则、Swift自定义规则(简介)、、编译器日志工作流
swiftlint analyze - SwiftLint官方文档 — 官方文档
- SwiftLint规则目录 — 完整分类规则列表
- SimplyDanny/SwiftLintPlugins — 推荐的插件包