遍历枚举值 [英] looping through enum values

查看:29
本文介绍了遍历枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Objective-C 中循环遍历枚举值?

Is it possible to loop through enum values in Objective-C?

推荐答案

Given

enum Foo {Bar=0,Baz,...,Last};

您可以迭代元素,例如:

you can iterate the elements like:

for(int i=Bar; i<=Last; i++) {
  ...
}

请注意,这暴露了 C 枚举的真正简单的性质.特别是,您可以看到 C 枚举并没有真正提供类型安全,因为您可以使用 int 代替枚举值,反之亦然.此外,这取决于枚举值的声明顺序:至少可以说是脆弱的.另外,请看查克的评论;如果枚举项不连续(例如,因为您为某些项指定了显式的、非连续的值),则这根本不起作用.哎呀.

Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa. In addition, this depends on the declaration order of the enum values: fragile to say the least. In addition, please see Chuck's comment; if the enum items are non-contiguous (e.g. because you specified explicit, non-sequential values for some items), this won't work at all. Yikes.

这篇关于遍历枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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