skip to content

In SwiftLint's .swiftlint.yml, how do you write a custom_rules entry that bans print() in production code without flagging strings, comments or tests?

level: middleimportance: should knowfreq 45%

answer

  1. a regex rule with its own identifier
  2. filter matches by syntax kind
  3. match_kinds: identifier
  4. path filters here are regular expressions
  5. only_rules must list custom_rules

basics

~20 s

Add a custom_rules entry with a regex for print(, match_kinds: identifier so matches inside strings and comments are dropped, an excluded path regex for test files, and a message and severity; with only_rules, list custom_rules too.

solid answer

~40 s

Under `custom_rules` you name a rule (say `no_print`) and give it a `regex` such as `\bprint\s*\(`. `match_kinds: [identifier]` rejects any match that touches a syntax kind outside the list, so `"print("` in a string or a commented-out call is not reported. The rule's own `included` and `excluded` take **regular expressions matched against the file path**, unlike the top-level path lists, so `excluded: ".*Tests/.*"` skips test files. Set `message` and `severity: error` (the default is a warning with the message "Regex matched"). If the file uses `only_rules`, the literal `custom_rules` must be in it, and developers can still suppress one line with `// swiftlint:disable:next no_print`.

code

yaml · 10 lines
yaml
custom_rules:
  no_print:
    name: "No print"
    regex: "\\bprint\\s*\\("
    match_kinds:
      - identifier
    excluded:
      - ".*Tests/.*\\.swift"
    message: "Use the claims logger instead of print()."
    severity: error

go deeper

for a junior

Recall that custom_rules holds named regex rules with a regex, message and severity, and that each name works as a rule identifier.

for a middle

Explain how match_kinds filters matches by SourceKit syntax kind and why the rule's path filters are regular expressions, not globs.

for a senior

Anticipate the regex's false positives, the s and m flags running .* across lines, and the only_rules trap, and test the rule on real code before raising it to error.

for a principal

Decide which bans deserve a regex rule at all, knowing it sees text rather than types and cannot autocorrect, against relying on code review.

## What a regex custom rule is SwiftLint can run **regex custom rules** defined in `.swiftlint.yml` under the `custom_rules` key. Each entry is keyed by its own **rule identifier**, which then behaves like a built-in identifier: it shows up in reports, can be suppressed with `// swiftlint:disable:next no_print`, and is listed in baselines. Regex rules work with official SwiftLint builds. A second kind, Swift custom rules written against SwiftSyntax, requires building SwiftLint yourself with Bazel, which is a much bigger commitment. The insurance-claims app wants `print()` gone from production code in favour of the app's logger, while tests may keep it. ```yaml custom_rules: no_print: name: "No print" regex: "\\bprint\\s*\\(" match_kinds: - identifier excluded: - ".*Tests/.*\\.swift" message: "Use the claims logger instead of print()." severity: error ``` In YAML double quotes, `\\b` becomes the regex `\b`, so the pattern is `\bprint\s*\(`: the word `print` followed by an opening parenthesis. The word boundary keeps `debugPrint(` from matching, and `\s*` still catches `print (x)` written with a space. ## The keys of one entry | Key | Meaning | Default | |---|---|---| | `regex` | the pattern to report | required | | `match_kinds` | syntax kinds a match may contain | all kinds | | `excluded_match_kinds` | syntax kinds a match must not contain | none | | `included` / `excluded` | regular expressions matched against the file path | every file | | `name` | display name | the identifier | | `message` | the violation text | "Regex matched" | | `severity` | `warning` or `error` | `warning` | | `capture_group` | which group to highlight | 0, the whole match | ## Filtering by syntax kind A plain regex sees text, so it would report `print(` inside a string literal, a doc comment or a line commented out during debugging. SwiftLint asks SourceKit for the **syntax kind** of every token and filters matches: - With `match_kinds`, a match is **rejected if it includes any syntax kind not in the list**. `print` in a call is an `identifier`; the parenthesis and spaces carry no kind, so a real call survives while a match inside a `string` or `comment` token is dropped. - `excluded_match_kinds` is the inverse: list the kinds to reject, for example `comment`, `doccomment` and `string`. - The two keys **cannot appear at the same time**; SwiftLint reports that as a configuration problem. The README lists the valid kinds, among them `argument`, `comment`, `doccomment`, `identifier`, `keyword`, `number`, `string` and `typeidentifier`. A name outside that list makes the entry an invalid configuration. ## Paths: two different grammars The top-level `included` and `excluded` keys of `.swiftlint.yml` are **paths with wildcards**, relative to the configuration file (`Pods`, `Sources/*/Generated.swift`). The `included` and `excluded` keys **inside a custom rule** are **regular expressions** tested against the file's path. Writing a glob such as `**/Tests/**` there fails, because a leading `*` is not a valid regular expression and SwiftLint reports an invalid regex pattern for the rule; `.*Tests/.*` is the regex form. A file the top-level `excluded` list removes is not linted by any rule, custom or built-in. ## Regex details that bite 1. SwiftLint compiles the pattern with the `s` and `m` options: `.` matches newlines and `^`/`$` match at line boundaries. A greedy `.*` can therefore run across lines; prefix the pattern with `(?-s)` to keep `.` on one line. 2. `capture_group` must exist in the pattern; a number larger than the pattern's group count is rejected. 3. A regex rule has no autocorrection, so `swiftlint --fix` leaves every match for a human. 4. A regex cannot see types. `\bprint\s*\(` also matches a method named `print(` on one of your own types; the honest options are a narrower pattern, a rename, or a reviewed suppression on that line. ## Turning it on alongside other rules Custom rules run whenever the `custom_rules` key is present and the rule set is the default-plus-adjustments form. With `only_rules`, you must include the literal string `custom_rules` in the list, and then every rule under `custom_rules` runs. Disabling `custom_rules` by identifier, or with `// swiftlint:disable:next custom_rules`, switches off all of them at once. How strict the team is about banning a call is a question of lint philosophy; the mechanics above are what SwiftLint offers to enforce it.

  • The team uses only_rules and the new no_print rule never fires. Why?
    With `only_rules`, SwiftLint runs nothing that is not listed, and regex rules count only when the literal `custom_rules` is in that list. Add `custom_rules` to `only_rules`; every rule defined under `custom_rules` then runs.
  • Why might excluded: "**/Tests/**" inside the custom rule fail to skip test files?
    Inside a custom rule, `included` and `excluded` are regular expressions matched against the file path, not globs. `**/Tests/**` is not a valid regular expression, so SwiftLint reports an invalid regex pattern for the rule; write `.*Tests/.*` instead. Globs belong to the top-level `excluded` list.

  • A custom rule's excluded list takes the same globs as the top-level excluded.
  • match_kinds and excluded_match_kinds can be combined in one rule.
  • A plain regex already ignores matches inside string literals.
  • swiftlint --fix can rewrite custom rule violations.
  • Regex custom rules require building SwiftLint from source.
  • Custom rules run under only_rules without listing custom_rules.