Prefer Condition List

Prefer a condition list over chaining conditions with ‘&&’

  • Identifier: prefer_condition_list
  • Enabled by default: No
  • Supports autocorrection: Yes
  • Kind: idiomatic
  • Analyzer rule: No
  • Minimum Swift compiler version: 5.0.0
  • Default configuration:
    KeyValue
    severity warning

Rationale

Instead of chaining conditions with &&, use a condition list to separate conditions with commas, that is, use

if a, b {}

instead of

if a && b {}

Using a condition list improves readability and makes it easier to add or remove conditions in the future. It also allows for better formatting and alignment of conditions. All in all, it’s the idiomatic way to write conditions in Swift.

Since function calls with trailing closures trigger a warning in the Swift compiler when used in conditions, this rule makes sure to wrap such expressions in parentheses when transforming them to condition list elements. The scope of the parentheses is limited to the function call itself.

Non Triggering Examples

if a, b {}
guard a || b && c {}
if a && b || c {}
let result = a && b
repeat {} while a && b
if (f {}) {}
if f {} {}

Triggering Examples

if a && b {}
if a && b && c {}
while a && b {}
guard a && b {}
guard (a || b) && c {}
if a && (b && c) {}
guard a && b && c else {}
if (a && b) {}
if (a && f {}) {}