Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-In Loops multiple conditions

With the new update to Xcode 7.3, a lot of issues appeared related with the new version of Swift 3. One of them says "C-style for statement is deprecated and will be removed in a future version of Swift" (this appears in traditional for statements).

One of this loops has more than one condition:

for i = 0; i < 5 && i < products.count; i += 1 {

}

My question is, is there any elegant way (not use break) to include this double condition in a for-in loop of Swift:

for i in 0 ..< 5 {

}
like image 424
angeldev Avatar asked Mar 24 '16 16:03

angeldev


People also ask

Can a for loop have multiple conditions?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

Can we put multiple conditions in for loop in Java?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.


1 Answers

You can use && operator with where condition like

let arr = [1,2,3,4,5,6,7,8,9]

for i in 1...arr.count where i < 5  {
    print(i)
}
//output:- 1 2 3 4

for i in 1...100 where i > 40 && i < 50 && (i % 2 == 0) {
     print(i)
}
//output:- 42 44 46 48
like image 100
EI Captain v2.0 Avatar answered Oct 01 '22 19:10

EI Captain v2.0