File: RuleDocumentation.md

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (554 lines) | stat: -rw-r--r-- 20,394 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
<!-- This file is automatically generated with generate-swift-format. Do not edit! -->

# `swift-format` Lint and Format Rules

Use the rules below in the `rules` block of your `.swift-format`
configuration file, as described in
[Configuration](Configuration.md). All of these rules can be
applied in the linter, but only some of them can format your source code
automatically.

Here's the list of available rules:

- [AllPublicDeclarationsHaveDocumentation](#AllPublicDeclarationsHaveDocumentation)
- [AlwaysUseLiteralForEmptyCollectionInit](#AlwaysUseLiteralForEmptyCollectionInit)
- [AlwaysUseLowerCamelCase](#AlwaysUseLowerCamelCase)
- [AmbiguousTrailingClosureOverload](#AmbiguousTrailingClosureOverload)
- [BeginDocumentationCommentWithOneLineSummary](#BeginDocumentationCommentWithOneLineSummary)
- [DoNotUseSemicolons](#DoNotUseSemicolons)
- [DontRepeatTypeInStaticProperties](#DontRepeatTypeInStaticProperties)
- [FileScopedDeclarationPrivacy](#FileScopedDeclarationPrivacy)
- [FullyIndirectEnum](#FullyIndirectEnum)
- [GroupNumericLiterals](#GroupNumericLiterals)
- [IdentifiersMustBeASCII](#IdentifiersMustBeASCII)
- [NeverForceUnwrap](#NeverForceUnwrap)
- [NeverUseForceTry](#NeverUseForceTry)
- [NeverUseImplicitlyUnwrappedOptionals](#NeverUseImplicitlyUnwrappedOptionals)
- [NoAccessLevelOnExtensionDeclaration](#NoAccessLevelOnExtensionDeclaration)
- [NoAssignmentInExpressions](#NoAssignmentInExpressions)
- [NoBlockComments](#NoBlockComments)
- [NoCasesWithOnlyFallthrough](#NoCasesWithOnlyFallthrough)
- [NoEmptyTrailingClosureParentheses](#NoEmptyTrailingClosureParentheses)
- [NoLabelsInCasePatterns](#NoLabelsInCasePatterns)
- [NoLeadingUnderscores](#NoLeadingUnderscores)
- [NoParensAroundConditions](#NoParensAroundConditions)
- [NoPlaygroundLiterals](#NoPlaygroundLiterals)
- [NoVoidReturnOnFunctionSignature](#NoVoidReturnOnFunctionSignature)
- [OmitExplicitReturns](#OmitExplicitReturns)
- [OneCasePerLine](#OneCasePerLine)
- [OneVariableDeclarationPerLine](#OneVariableDeclarationPerLine)
- [OnlyOneTrailingClosureArgument](#OnlyOneTrailingClosureArgument)
- [OrderedImports](#OrderedImports)
- [ReplaceForEachWithForLoop](#ReplaceForEachWithForLoop)
- [ReturnVoidInsteadOfEmptyTuple](#ReturnVoidInsteadOfEmptyTuple)
- [TypeNamesShouldBeCapitalized](#TypeNamesShouldBeCapitalized)
- [UseEarlyExits](#UseEarlyExits)
- [UseExplicitNilCheckInConditions](#UseExplicitNilCheckInConditions)
- [UseLetInEveryBoundCaseVariable](#UseLetInEveryBoundCaseVariable)
- [UseShorthandTypeNames](#UseShorthandTypeNames)
- [UseSingleLinePropertyGetter](#UseSingleLinePropertyGetter)
- [UseSynthesizedInitializer](#UseSynthesizedInitializer)
- [UseTripleSlashForDocumentationComments](#UseTripleSlashForDocumentationComments)
- [UseWhereClausesInForLoops](#UseWhereClausesInForLoops)
- [ValidateDocumentationComments](#ValidateDocumentationComments)

### AllPublicDeclarationsHaveDocumentation

All public or open declarations must have a top-level documentation comment.

Lint: If a public declaration is missing a documentation comment, a lint error is raised.

`AllPublicDeclarationsHaveDocumentation` is a linter-only rule.

### AlwaysUseLiteralForEmptyCollectionInit

Never use `[<Type>]()` syntax. In call sites that should be replaced with `[]`,
for initializations use explicit type combined with empty array literal `let _: [<Type>] = []`
Static properties of a type that return that type should not include a reference to their type.

Lint:  Non-literal empty array initialization will yield a lint error.
Format: All invalid use sites would be related with empty literal (with or without explicit type annotation).

`AlwaysUseLiteralForEmptyCollectionInit` rule can format your code automatically.

### AlwaysUseLowerCamelCase

All values should be written in lower camel-case (`lowerCamelCase`).
Underscores (except at the beginning of an identifier) are disallowed.

This rule does not apply to test code, defined as code which:
  * Contains the line `import XCTest`

Lint: If an identifier contains underscores or begins with a capital letter, a lint error is
      raised.

`AlwaysUseLowerCamelCase` is a linter-only rule.

### AmbiguousTrailingClosureOverload

Overloads with only a closure argument should not be disambiguated by parameter labels.

Lint: If two overloaded functions with one closure parameter appear in the same scope, a lint
      error is raised.

`AmbiguousTrailingClosureOverload` is a linter-only rule.

### BeginDocumentationCommentWithOneLineSummary

All documentation comments must begin with a one-line summary of the declaration.

Lint: If a comment does not begin with a single-line summary, a lint error is raised.

`BeginDocumentationCommentWithOneLineSummary` is a linter-only rule.

### DoNotUseSemicolons

Semicolons should not be present in Swift code.

Lint: If a semicolon appears anywhere, a lint error is raised.

Format: All semicolons will be replaced with line breaks.

`DoNotUseSemicolons` rule can format your code automatically.

### DontRepeatTypeInStaticProperties

Static properties of a type that return that type should not include a reference to their type.

"Reference to their type" means that the property name includes part, or all, of the type. If
the type contains a namespace (i.e. `UIColor`) the namespace is ignored;
`public class var redColor: UIColor` would trigger this rule.

Lint: Static properties of a type that return that type will yield a lint error.

`DontRepeatTypeInStaticProperties` is a linter-only rule.

### FileScopedDeclarationPrivacy

Declarations at file scope with effective private access should be consistently declared as
either `fileprivate` or `private`, determined by configuration.

Lint: If a file-scoped declaration has formal access opposite to the desired access level in the
      formatter's configuration, a lint error is raised.

Format: File-scoped declarations that have formal access opposite to the desired access level in
        the formatter's configuration will have their access level changed.

`FileScopedDeclarationPrivacy` rule can format your code automatically.

### FullyIndirectEnum

If all cases of an enum are `indirect`, the entire enum should be marked `indirect`.

Lint: If every case of an enum is `indirect`, but the enum itself is not, a lint error is
      raised.

Format: Enums where all cases are `indirect` will be rewritten such that the enum is marked
        `indirect`, and each case is not.

`FullyIndirectEnum` rule can format your code automatically.

### GroupNumericLiterals

Numeric literals should be grouped with `_`s to delimit common separators.

Specifically, decimal numeric literals should be grouped every 3 numbers, hexadecimal every 4,
and binary every 8.

Lint: If a numeric literal is too long and should be grouped, a lint error is raised.

Format: All numeric literals that should be grouped will have `_`s inserted where appropriate.

TODO: Minimum numeric literal length bounds and numeric groupings have been selected arbitrarily;
these could be reevaluated.
TODO: Handle floating point literals.

`GroupNumericLiterals` rule can format your code automatically.

### IdentifiersMustBeASCII

All identifiers must be ASCII.

Lint: If an identifier contains non-ASCII characters, a lint error is raised.

`IdentifiersMustBeASCII` is a linter-only rule.

### NeverForceUnwrap

Force-unwraps are strongly discouraged and must be documented.

This rule does not apply to test code, defined as code which:
  * Contains the line `import XCTest`

Lint: If a force unwrap is used, a lint warning is raised.

`NeverForceUnwrap` is a linter-only rule.

### NeverUseForceTry

Force-try (`try!`) is forbidden.

This rule does not apply to test code, defined as code which:
  * Contains the line `import XCTest`

Lint: Using `try!` results in a lint error.

TODO: Create exception for NSRegularExpression

`NeverUseForceTry` is a linter-only rule.

### NeverUseImplicitlyUnwrappedOptionals

Implicitly unwrapped optionals (e.g. `var s: String!`) are forbidden.

Certain properties (e.g. `@IBOutlet`) tied to the UI lifecycle are ignored.

This rule does not apply to test code, defined as code which:
  * Contains the line `import XCTest`

TODO: Create exceptions for other UI elements (ex: viewDidLoad)

Lint: Declaring a property with an implicitly unwrapped type yields a lint error.

`NeverUseImplicitlyUnwrappedOptionals` is a linter-only rule.

### NoAccessLevelOnExtensionDeclaration

Specifying an access level for an extension declaration is forbidden.

Lint: Specifying an access level for an extension declaration yields a lint error.

Format: The access level is removed from the extension declaration and is added to each
        declaration in the extension; declarations with redundant access levels (e.g.
        `internal`, as that is the default access level) have the explicit access level removed.

`NoAccessLevelOnExtensionDeclaration` rule can format your code automatically.

### NoAssignmentInExpressions

Assignment expressions must be their own statements.

Assignment should not be used in an expression context that expects a `Void` value. For example,
assigning a variable within a `return` statement existing a `Void` function is prohibited.

Lint: If an assignment expression is found in a position other than a standalone statement, a
      lint finding is emitted.

Format: A `return` statement containing an assignment expression is expanded into two separate
        statements.

`NoAssignmentInExpressions` rule can format your code automatically.

### NoBlockComments

Block comments should be avoided in favor of line comments.

Lint: If a block comment appears, a lint error is raised.

`NoBlockComments` is a linter-only rule.

### NoCasesWithOnlyFallthrough

Cases that contain only the `fallthrough` statement are forbidden.

Lint: Cases containing only the `fallthrough` statement yield a lint error.

Format: The fallthrough `case` is added as a prefix to the next case unless the next case is
        `default`; in that case, the fallthrough `case` is deleted.

`NoCasesWithOnlyFallthrough` rule can format your code automatically.

### NoEmptyTrailingClosureParentheses

Function calls with no arguments and a trailing closure should not have empty parentheses.

Lint: If a function call with a trailing closure has an empty argument list with parentheses,
      a lint error is raised.

Format: Empty parentheses in function calls with trailing closures will be removed.

`NoEmptyTrailingClosureParentheses` rule can format your code automatically.

### NoLabelsInCasePatterns

Redundant labels are forbidden in case patterns.

In practice, *all* case pattern labels should be redundant.

Lint: Using a label in a case statement yields a lint error unless the label does not match the
      binding identifier.

Format: Redundant labels in case patterns are removed.

`NoLabelsInCasePatterns` rule can format your code automatically.

### NoLeadingUnderscores

Identifiers in declarations and patterns should not have leading underscores.

This is intended to avoid certain antipatterns; `self.member = member` should be preferred to
`member = _member` and the leading underscore should not be used to signal access level.

This rule intentionally checks only the parameter variable names of a function declaration, not
the parameter labels. It also only checks identifiers at the declaration site, not at usage
sites.

Lint: Declaring an identifier with a leading underscore yields a lint error.

`NoLeadingUnderscores` is a linter-only rule.

### NoParensAroundConditions

Enforces rules around parentheses in conditions or matched expressions.

Parentheses are not used around any condition of an `if`, `guard`, or `while` statement, or
around the matched expression in a `switch` statement.

Lint: If a top-most expression in a `switch`, `if`, `guard`, or `while` statement is surrounded
      by parentheses, and it does not include a function call with a trailing closure, a lint
      error is raised.

Format: Parentheses around such expressions are removed, if they do not cause a parse ambiguity.
        Specifically, parentheses are allowed if and only if the expression contains a function
        call with a trailing closure.

`NoParensAroundConditions` rule can format your code automatically.

### NoPlaygroundLiterals

The playground literals (`#colorLiteral`, `#fileLiteral`, and `#imageLiteral`) are forbidden.

Lint: Using a playground literal will yield a lint error with a suggestion of an API to replace
it.

`NoPlaygroundLiterals` is a linter-only rule.

### NoVoidReturnOnFunctionSignature

Functions that return `()` or `Void` should omit the return signature.

Lint: Function declarations that explicitly return `()` or `Void` will yield a lint error.

Format: Function declarations with explicit returns of `()` or `Void` will have their return
        signature stripped.

`NoVoidReturnOnFunctionSignature` rule can format your code automatically.

### OmitExplicitReturns

Single-expression functions, closures, subscripts can omit `return` statement.

Lint: `func <name>() { return ... }` and similar single expression constructs will yield a lint error.

Format: `func <name>() { return ... }` constructs will be replaced with
        equivalent `func <name>() { ... }` constructs.

`OmitExplicitReturns` rule can format your code automatically.

### OneCasePerLine

Each enum case with associated values or a raw value should appear in its own case declaration.

Lint: If a single `case` declaration declares multiple cases, and any of them have associated
      values or raw values, a lint error is raised.

Format: All case declarations with associated values or raw values will be moved to their own
        case declarations.

`OneCasePerLine` rule can format your code automatically.

### OneVariableDeclarationPerLine

Each variable declaration, with the exception of tuple destructuring, should
declare 1 variable.

Lint: If a variable declaration declares multiple variables, a lint error is
raised.

Format: If a variable declaration declares multiple variables, it will be
split into multiple declarations, each declaring one of the variables, as
long as the result would still be syntactically valid.

`OneVariableDeclarationPerLine` rule can format your code automatically.

### OnlyOneTrailingClosureArgument

Function calls should never mix normal closure arguments and trailing closures.

Lint: If a function call with a trailing closure also contains a non-trailing closure argument,
      a lint error is raised.

`OnlyOneTrailingClosureArgument` is a linter-only rule.

### OrderedImports

Imports must be lexicographically ordered and logically grouped at the top of each source file.
The order of the import groups is 1) regular imports, 2) declaration imports, and 3) @testable
imports. These groups are separated by a single blank line. Blank lines in between the import
declarations are removed.

Lint: If an import appears anywhere other than the beginning of the file it resides in,
      not lexicographically ordered, or  not in the appropriate import group, a lint error is
      raised.

Format: Imports will be reordered and grouped at the top of the file.

`OrderedImports` rule can format your code automatically.

### ReplaceForEachWithForLoop

Replace `forEach` with `for-in` loop unless its argument is a function reference.

Lint:  invalid use of `forEach` yield will yield a lint error.

`ReplaceForEachWithForLoop` is a linter-only rule.

### ReturnVoidInsteadOfEmptyTuple

Return `Void`, not `()`, in signatures.

Note that this rule does *not* apply to function declaration signatures in order to avoid
conflicting with `NoVoidReturnOnFunctionSignature`.

Lint: Returning `()` in a signature yields a lint error.

Format: `-> ()` is replaced with `-> Void`

`ReturnVoidInsteadOfEmptyTuple` rule can format your code automatically.

### TypeNamesShouldBeCapitalized

`struct`, `class`, `enum` and `protocol` declarations should have a capitalized name.

Lint:  Types with un-capitalized names will yield a lint error.

`TypeNamesShouldBeCapitalized` is a linter-only rule.

### UseEarlyExits

Early exits should be used whenever possible.

This means that `if ... else { return/throw/break/continue }` constructs should be replaced by
`guard ... else { return/throw/break/continue }` constructs in order to keep indentation levels
low. Specifically, code of the following form:

```swift
if condition {
  trueBlock
} else {
  falseBlock
  return/throw/break/continue
}
```

will be transformed into:

```swift
guard condition else {
  falseBlock
  return/throw/break/continue
}
trueBlock
```

Lint: `if ... else { return/throw/break/continue }` constructs will yield a lint error.

Format: `if ... else { return/throw/break/continue }` constructs will be replaced with
        equivalent `guard ... else { return/throw/break/continue }` constructs.

`UseEarlyExits` rule can format your code automatically.

### UseExplicitNilCheckInConditions

When checking an optional value for `nil`-ness, prefer writing an explicit `nil` check rather
than binding and immediately discarding the value.

For example, `if let _ = someValue { ... }` is forbidden. Use `if someValue != nil { ... }`
instead.

Lint: `let _ = expr` inside a condition list will yield a lint error.

Format: `let _ = expr` inside a condition list will be replaced by `expr != nil`.

`UseExplicitNilCheckInConditions` rule can format your code automatically.

### UseLetInEveryBoundCaseVariable

Every variable bound in a `case` pattern must have its own `let/var`.

For example, `case let .identifier(x, y)` is forbidden. Use
`case .identifier(let x, let y)` instead.

Lint: `case let .identifier(...)` will yield a lint error.

`UseLetInEveryBoundCaseVariable` is a linter-only rule.

### UseShorthandTypeNames

Shorthand type forms must be used wherever possible.

Lint: Using a non-shorthand form (e.g. `Array<Element>`) yields a lint error unless the long
      form is necessary (e.g. `Array<Element>.Index` cannot be shortened today.)

Format: Where possible, shorthand types replace long form types; e.g. `Array<Element>` is
        converted to `[Element]`.

`UseShorthandTypeNames` rule can format your code automatically.

### UseSingleLinePropertyGetter

Read-only computed properties must use implicit `get` blocks.

Lint: Read-only computed properties with explicit `get` blocks yield a lint error.

Format: Explicit `get` blocks are rendered implicit by removing the `get`.

`UseSingleLinePropertyGetter` rule can format your code automatically.

### UseSynthesizedInitializer

When possible, the synthesized `struct` initializer should be used.

This means the creation of a (non-public) memberwise initializer with the same structure as the
synthesized initializer is forbidden.

Lint: (Non-public) memberwise initializers with the same structure as the synthesized
      initializer will yield a lint error.

`UseSynthesizedInitializer` is a linter-only rule.

### UseTripleSlashForDocumentationComments

Documentation comments must use the `///` form.

This is similar to `NoBlockComments` but is meant to prevent documentation block comments.

Lint: If a doc block comment appears, a lint error is raised.

Format: If a doc block comment appears on its own on a line, or if a doc block comment spans
        multiple lines without appearing on the same line as code, it will be replaced with
        multiple doc line comments.

`UseTripleSlashForDocumentationComments` rule can format your code automatically.

### UseWhereClausesInForLoops

`for` loops that consist of a single `if` statement must use `where` clauses instead.

Lint: `for` loops that consist of a single `if` statement yield a lint error.

Format: `for` loops that consist of a single `if` statement have the conditional of that
        statement factored out to a `where` clause.

`UseWhereClausesInForLoops` rule can format your code automatically.

### ValidateDocumentationComments

Documentation comments must be complete and valid.

"Command + Option + /" in Xcode produces a minimal valid documentation comment.

Lint: Documentation comments that are incomplete (e.g. missing parameter documentation) or
      invalid (uses `Parameters` when there is only one parameter) will yield a lint error.

`ValidateDocumentationComments` is a linter-only rule.