Swift Coding Standards Using Loops
Best practises of how to use loops in swift for iOS
In this story we will see the best practises and coding standards in order to use correctly loops (for/while) statements in swift.
If you also want to see more best practises for Swift for more general items you can check this article
Let’s now see some cases to use correctly the “for” statement.
For - Where Loops
Let’s suppose we have an array of objects that they contain a boolean (for this tutorial let’s call it “isFavorite”). Now most of people creates the loop and then with an “if” statement they check the boolean value. In swift can be done easily using the “where” statement.
Not preferred
for movie in movies {
if movie.isFavorite {
// do stuff
}
}
Preferred
for movie in movies where movie.isFavorite {
// do stuff
}