如何在for循环中跟踪数组索引? [重复]

时间:2021-11-06 17:54:53

This question already has an answer here:

这个问题在这里已有答案:

If I write:

如果我写:

 for (NSString* word in self.words)
{

}

And I want to keep track of my position in the array, how can I do that? Of course, I know I can just create an int and increment it as I loop, a.k.a. the old-fashioned way. I guess I'm just looking to see if there's an opportunity here to learn something. Like in python we have the handy enumerate() function for this sort of thing which gives you indices paired with objects.

我想跟踪我在阵列中的位置,我该怎么做?当然,我知道我可以创建一个int并将其递增,因为我循环,a.k.a。老式的方式。我想我只是想看看这里是否有机会学习一些东西。就像在python中一样,我们为这种东西提供了方便的enumerate()函数,它为你提供了与对象配对的索引。

1 个解决方案

#1


1  

You could use [words indexOfObject:word]; but caution: if you have equal object in an array, it will return the first object's index. also this shows, that it is awfully inefficient — if will iterate over the array for each call.

你可以使用[words indexOfObject:word];但要注意:如果数组中有相同的对象,它将返回第一个对象的索引。这也表明,它是非常低效的 - 如果将为每个调用迭代数组。

better:

更好:

[words enumerateObjectsUsingBlocks:^(NSString *word,
                                     NSUInteger idx,
                                     BOOL *stop)
{
    //
}];

as it gives you enumeration AND the index at the same time.

因为它同时为您提供枚举和索引。

documentation

文件

#1


1  

You could use [words indexOfObject:word]; but caution: if you have equal object in an array, it will return the first object's index. also this shows, that it is awfully inefficient — if will iterate over the array for each call.

你可以使用[words indexOfObject:word];但要注意:如果数组中有相同的对象,它将返回第一个对象的索引。这也表明,它是非常低效的 - 如果将为每个调用迭代数组。

better:

更好:

[words enumerateObjectsUsingBlocks:^(NSString *word,
                                     NSUInteger idx,
                                     BOOL *stop)
{
    //
}];

as it gives you enumeration AND the index at the same time.

因为它同时为您提供枚举和索引。

documentation

文件