Obj-C 中 For 语句中的多个循环变量
有没有办法在 for 语句中使用多个循环变量?以下是我所讨论内容的假设表示:
for (NSString *foo in bar; NSString *bob in example) {}
如果不是,什么是实现此目的的好方法?
谢谢,
科林
Is there a way to have multiple loop variables in a for statement? Here would be a hypothetical representation of what I'm talking about:
for (NSString *foo in bar;
NSString *bob in example) {}
If not what is a good way to accomplish this?
Thanks,
Kolin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Joshua 是对的,没有办法用快速枚举语法来做到这一点,但有几种方法(至少)可以实现类似的目标。您喜欢哪种方法取决于您是否试图避免运行两次循环的开销,或者是否试图避免代码中存在两个单独的循环带来的视觉混乱。
假设你有两个 NSString 集合(顺便说一句,它们不需要是 NSArrays)
如果你想迭代两个集合的所有元素,你可以执行以下操作:
这将首先迭代 bar 的所有元素,然后遍历示例的所有元素(即它将输出:bar1、bar2、bar3、bar4、bar5、example1、example2)。
如果您想最大限度地减少循环的迭代次数,并且不一定需要遍历两个集合的所有元素,您可以尝试将上面的 while 循环替换为:
这将同时循环遍历两个集合,但一旦其中一个集合耗尽了元素(即它将输出:bar1、example1、bar2、example2),
但请注意,循环对性能产生有意义的影响的情况非常罕见,因此如果这都是为了避免运行时成本两个循环可能会通过其他优化得到更好的服务。
Joshua is right that there's no way to do it with fast enumeration syntax but there's a couple of ways (at least) you can achieve something similar. Which approach you prefer depends on whether you're trying avoid the overhead of running the loop twice or whether you're trying to avoid the visual clutter of having two separate loops in your code.
Assuming you have two collections of NSStrings (they don't need to be NSArrays btw)
If you're looking to iterate over all the elements of both collections you can do the following:
this will iterate over all of bar's elements first and then over all of example's elements (i.e. it will output: bar1, bar2, bar3, bar4, bar5, example1, example2).
if you want to minimize the number of iterations of the loop and don't necessarily need to run through all the elements of both collections you can try replacing the while loop above with:
This will loop through both collections simultaneously but will stop as soon as one of the collections runs out of elements (i.e. it will output: bar1, example1, bar2, example2)
Just as a note though, it's pretty rare that loops have a meaningful impact on performance so if this is all to avoid the runtime cost of two loops you're likely better served by other optimizations.
不,无论如何都不使用快速枚举语法。
No, not using the fast enumeration syntax anyway.
假设有块,另一种选择:
Assuming blocks, an alternative: