For-In循环多个条件

ang*_*dev 6 swift swift3 xcode7.3

随着Xcode 7.3的新更新,出现了许多与Swift 3新版本相关的问题.其中一个问题是"C-style for statement已被弃用,将在未来版本的Swift中删除"(这在传统版本中出现)for语句).

其中一个循环有多个条件:

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

}
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有任何优雅的方式(不使用break)在Swift的for-in循环中包含这个双重条件:

for i in 0 ..< 5 {

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ier 15

如果你大声描述它就像你说的那样:

for i in 0 ..< min(5, products.count) { ... }
Run Code Online (Sandbox Code Playgroud)

不过,我怀疑你真正的意思是:

for product in products.prefix(5) { ... }
Run Code Online (Sandbox Code Playgroud)

这比任何需要下标的东西都更不容易出错.

你可能真的需要一个整数索引(虽然这很少见),在这种情况下你的意思是:

for (index, product) in products.enumerate().prefix(5) { ... }
Run Code Online (Sandbox Code Playgroud)

或者你甚至可以得到一个真正的索引,如果你想:

for (index, product) in zip(products.indices, products).prefix(5) { ... }
Run Code Online (Sandbox Code Playgroud)

  • 你的答案完全证明了为什么Apple正在删除C风格的`for`语句:因为还有其他更多Swifty方法可以完成同样的事情,而且人们通常只使用旧式`for`语句来迭代数组. (3认同)

EI *_*2.0 15

您可以使用&&具有where条件的运算符

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
Run Code Online (Sandbox Code Playgroud)


Sam*_*rad 5

这样做的另一种方式是这样的

for i in 0 ..< 5 where i < products.count {
}
Run Code Online (Sandbox Code Playgroud)