For-In Loops multiple conditions

2020-04-06 01:10发布

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 {

}

5条回答
迷人小祖宗
2楼-- · 2020-04-06 01:26

Here’s a simple solution:

var x = 0
while (x < foo.length && x < bar.length) {

  // Loop body goes here

  x += 1
}
查看更多
Lonely孤独者°
3楼-- · 2020-04-06 01:29

One more example. Loop through all UILabel in subviews:

for label in view.subviews where label is UILabel {
    print(label.text)
}
查看更多
▲ chillily
4楼-- · 2020-04-06 01:32

It would be just as you're saying if you described it out loud:

for i in 0 ..< min(5, products.count) { ... }

That said, I suspect you really mean:

for product in products.prefix(5) { ... }

which is less error-prone than anything that requires subscripting.

It's possible you actually need an integer index (though this is rare), in which case you mean:

for (index, product) in products.enumerate().prefix(5) { ... }

Or you could even get a real index if you wanted with:

for (index, product) in zip(products.indices, products).prefix(5) { ... }
查看更多
闹够了就滚
5楼-- · 2020-04-06 01:36

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
查看更多
forever°为你锁心
6楼-- · 2020-04-06 01:46

Another way to do so would be like this

for i in 0 ..< 5 where i < products.count {
}
查看更多
登录 后发表回答