7

随着 Xcode 7.3 的新更新,出现了很多与新版本 Swift 3 相关的问题。其中一个说“不推荐使用 C 样式的 for 语句,并将在未来版本的 Swift 中删除”(这出现在传统的for声明)。

此循环之一具有多个条件:

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

}

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

for i in 0 ..< 5 {

}
4

5 回答 5

18

您可以使用&&带有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
于 2016-06-22T10:31:24.393 回答
16

如果您大声描述它,就像您所说的那样:

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

也就是说,我怀疑你的意思是:

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

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

您实际上可能需要一个整数索引(尽管这种情况很少见),在这种情况下,您的意思是:

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

或者,如果您愿意,您甚至可以获得真正的索引:

for (index, product) in zip(products.indices, products).prefix(5) { ... }
于 2016-03-24T16:36:51.890 回答
6

另一种方法是这样的

for i in 0 ..< 5 where i < products.count {
}
于 2016-06-22T10:11:46.937 回答
1

再举一个例子。遍历子视图中的所有 UILabel:

for label in view.subviews where label is UILabel {
    print(label.text)
}
于 2018-09-25T18:38:57.173 回答
-1

这是一个简单的解决方案:

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

  // Loop body goes here

  x += 1
}
于 2017-04-06T16:15:50.777 回答