Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 433
Simon Avatar asked Dec 02 '14 00:12

Simon


People also ask

What is where in Swift?

You use where in Swift to filter things, kinda like a conditional. In various places throughout Swift, the “where” clause provides a constraint and a clear indicator of the data or types you want to work with. What's so special about where – as you'll soon see – is its flexible syntax.

What is stride in Swift?

Swift has a helpful stride() , which lets you move from one value to another using any increment – and even lets you specify whether the upper bound is exclusive or inclusive.

How do you stop a for loop in Swift?

Swift break statement with nested loops We can also use the break statement inside a nested loop. If we use break inside the inner loop, then the inner loop gets terminated. If we use break outside the inner loop, then the outer loop gets terminated.


2 Answers

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() } 
like image 51
Benjamin Gruenbaum Avatar answered Oct 25 '22 13:10

Benjamin Gruenbaum


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) } 
like image 26
Sunil Sharma Avatar answered Oct 25 '22 11:10

Sunil Sharma