It's a syntax that has been around for a long time, but I've noticed it recently, so I'll write it again. When writing Swift, I sometimes need to write code like this.
var count = 0
for i in 0..<n{
if condition(i){
count += 1
}
}
This is the case when there is ʻif directly under
for and there is no ʻelse
.
But if you use where
, you can write like this.
var count = 0
for i in 0..<n where condition(i){
count += 1
}
The meaning is simple, the where
clause specifies the condition. Writing this not only reduces the number of nests by one, but also makes it easier to understand the conditions you are thinking about.
Thanks to the optimization, there is no performance impact, so I think you should actively use it.
Recommended Posts