Prefer For-Where

where clauses are preferred over a single if inside a for

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

Non Triggering Examples

for user in users where user.id == 1 { }
for user in users {
  if let id = user.id { }
}
for user in users {
  if var id = user.id { }
}
for user in users {
  if user.id == 1 { } else { }
}
for user in users {
  if user.id == 1 {
  } else if user.id == 2 { }
}
for user in users {
  if user.id == 1 { }
  print(user)
}
for user in users {
  let id = user.id
  if id == 1 { }
}
for user in users {
  if user.id == 1 { }
  return true
}
for user in users {
  if user.id == 1 && user.age > 18 { }
}
for user in users {
  if user.id == 1, user.age > 18 { }
}
for (index, value) in array.enumerated() {
  if case .valueB(_) = value {
    return index
  }
}
//
// allow_for_as_filter: true
//

for user in users {
  if user.id == 1 { return true }
}

//
// allow_for_as_filter: true
//

for user in users {
  if user.id == 1 {
    let derivedValue = calculateValue(from: user)
    return derivedValue != 0
  }
}

Triggering Examples

for user in users {
  if user.id == 1 { return true }
}
for subview in subviews {
    if !(subview is UIStackView) {
        subview.removeConstraints(subview.constraints)
        subview.removeFromSuperview()
    }
}
//
// allow_for_as_filter: true
//

for subview in subviews {
    if !(subview is UIStackView) {
        subview.removeConstraints(subview.constraints)
        subview.removeFromSuperview()
    }
}