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

Simon picture Simon · Dec 2, 2014 · Viewed 23.9k times · Source

Is there also a possibility to use the 'where' keyword in another place then a switch? Can I use it in a for in loop for example?

I have an array with bools, all with a value, can I do something like this:

var boolArray: [Bool] = []

//(...) set values and do stuff


for value where value == true in boolArray {
   doSomething()
}

This would be a lot nicer than use an if, so I am wondering if there is a possibility to use where in combination with a for-loop. Ty for your time.

Answer

Benjamin Gruenbaum picture Benjamin Gruenbaum · Dec 2, 2014

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()
}