Can I use 'where' inside a for-loop in swift? Can I use 'where' inside a for-loop in swift? swift swift

Can I use 'where' inside a for-loop in swift?


In Swift 2, new where syntax was added:

for value in boolArray where value == true {   ...}

In Pre 2.0 one solution would be to call .filter on the array before you iterate it:

for value in boolArray.filter({ $0 == true }) {   doSomething()}


A normal for-loop will iterate all elements present in the list. But sometimes we want to iterate only when data satisfy some condition, there we can use where clause with for -loop. It's just a replacement of if condition inside the loop.

For example:

let numbers = [1,2,3,4,5,6,7]for data in numbers {    if (data % 2 == 0) {        print(data)    }}

can be rewritten in the simpler way as:

for data in numbers where data % 2 == 0 {    print(data)}


Yes, you can use "where" clause with for loop.

let arr = [1,2,3,4,5]for value in arr where value != 0 {    print(value)}

Considering your example,

var boolArray: [Bool] = []//(...) set values and do stufffor value in boolArray where value == true {   doSomething()}