[Swift] Use for where rather than nesting for and if

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

[Swift] Use for where rather than nesting for and if
C macros for watchOS and Swift API Availability
C macros for tvOS and Swift API Availability
Treat Swift functions and closures as C function pointers
Create UnsafeMutablePointer <UnsafeMutablePointer <Int8>?>! In Swift for C char ** hoge
[Swift] Use for where rather than nesting for and if
Use try-with-resources rather than try-finally
About for statement and if statement
Install Xcode and use Hello Swift!
[Swift / Beginner] Use Enum for maintainable coding
Criteria for proper use of render and redirect_to
C macros for watchOS and Swift API Availability
C macros for tvOS and Swift API Availability