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
}
As you can see you can write it in a single line with more clean code.
Loops Using enumerated
Use the enumerated()
function if you need to loop over a Sequence and use the index.
Avoid the use of forEach
except for simple one line closures.
Preferred
for (index, element) in someArray.enumerated() {
// do stuff
}
Loops Using joined
If you have an Array of Arrays and want to loop over all contents, consider a for in
loop using joined(separator:)
instead of nested loops:
Not preferred
for names in arraysOfNames {
for name in names {
print("\(name) is a person that...")
}
}
Preferred
for name in arraysOfNames.joined() {
print("\(name) is a person that...")
}
If you are enjoying my stories and you want to read more from me and a lot of other writers in medium, you can support me by joining medium through the following link (no extra costs for you)