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

问题描述

可以在Objective-C中循环枚举值吗?

解决方案

给定

 枚举Foo {Bar = 0,Baz,...,Last}; 

您可以迭代元素,如:

 for(int i = Bar; i  ... 
}
pre>

请注意,这暴露了C枚举的真正的纯粹性质。特别地,您可以看到,C枚举并不真正提供类型安全性,因为您可以使用int代替枚举值,反之亦然。另外,这取决于枚举值的声明顺序:最脆弱的说。另外,请参阅查克的评论;如果枚举项目是不连续的(例如因为您为某些项目指定了明确的非顺序值),那么这根本就不起作用。 Yikes。


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++) {
  ...
}

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.

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

07-26 15:46