For-In循环多个条件 [英] For-In Loops multiple conditions

查看:423
本文介绍了For-In循环多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着对Xcode 7.3的新更新,出现了许多与新版本的Swift 3相关的问题.其中一个问题是不赞成使用C风格的语句,而在以后的Swift版本中将删除它"(此出现在传统的for语句中.)

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 {

}

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

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 {

}

推荐答案

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

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) { ... }

这篇关于For-In循环多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆