`where` clauses are preferred over a single `if` inside a `for` loopSW-R1005
Prefer using where clauses over a single if statement to filter items inside a for loop. Using where clauses results in more readable and expressive code.
In Swift, it's common to use a for loop to iterate over a collection and apply some operation to each element. Often, only a subset of the elements satisfies certain conditions, and we want to filter them out before applying the operation. One way is to use an if statement inside the for loop to check the condition for each element. However, this approach can lead to nested if statements and less-readable code.
Instead, we can use a where clause to filter the elements that satisfy the condition. The where clause is placed after the for loop's variable binding and before the loop's body. It filters out the elements that don't satisfy the condition, resulting in more expressive code.
Bad Practice
for item in items {
if item.isValid {
// do something
}
}
Recommended
for item in items where item.isValid {
// do something
}
Using the filter
method:
let filteredItems = items.filter { $0.isValid }
for item in filteredItems {
// do something
}