如果集合中对象的类型已知,那么在使用快速枚举时是否应该指定迭代变量的类型?

发布于 2024-10-13 18:22:44 字数 619 浏览 5 评论 0原文

例如,假设我有一个包含一堆 NSString 对象的 NSArray

NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];

这样做的优点和缺点是什么:

for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}

与:

for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}

For example, say I have an NSArray that contains a bunch of NSString objects:

NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];

What are the pros and cons of doing this:

for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}

versus:

for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

揽月 2024-10-20 18:22:44

这并不是绝对必要的,并且会在每次迭代时强制转换为指定类型,因此除非您在循环内调用特定于 NSString 的方法,否则我不会不明白为什么这可能是有益的。

所以,在你的情况下我会这样做,因为你在每个对象上调用 -length (一个 NSString 方法)。为了避免编译器警告,您可以将对象强制转换为特定类型 - 这就是当您指定非 id 类型时 NSFastEnumeration 为您所做的事情。所以是的,使用你的第二个例子。

It's not strictly necessary, and will force a cast to the specified type on every iteration, so unless you are calling methods specific to NSString inside of your loop, then I don't see why this could be beneficial.

So, in your case I would do it, because you're invoking -length (an NSString method) on every object. In order to avoid compiler warnings, you'd cast the object to the specific type - which is what NSFastEnumeration does for you when you specify a non-id type. So yeah, use your second example.

黑凤梨 2024-10-20 18:22:44

如果您已经向迭代器传递了特定于类的消息,则无法通过将其类型指定为 id 来使其通用。如果您想让它“几乎”通用,您可以将层次结构中包含您计划使用的所有消息的最顶层类指定为迭代器类型。对于你的情况,这个类是 NSString

You can't make iterator universal by specifying it's type as id if you've already passed a class specific message to it. If you want to make it "almost" universal you can specify as iterator's type the top-most class in hierarchy having all messages you plan to use. For your case this class is NSString

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文