通过枚举值循环 [英] looping through enum values

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

问题描述

通过在Objective-C枚举值是否可以循环?

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

推荐答案

由于

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

您可以遍历的元素,如:

you can iterate the elements like:

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

请注意,这暴露了一个C枚举的真正-刚刚的-INT性质。特别是,你可以看到一个C枚举并没有真正提供类型安全,因为你可以在一个地方枚举值,反之亦然的使用int。此外,这取决于枚举值的声明顺序:脆弱的,至少可以说。此外,请参阅Chuck的意见;如果枚举项是不连续​​的(例如,因为您指定的某些项目明确,非连续值),这不会在所有的工作。让人惊讶。

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 visa 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天全站免登陆