我已经为我的 iPhone 应用程序创建了一个 typedef 枚举...
typedef enum {
FirstType,
SecondType,
ThirdType
} type;
只是为了测试,我希望能够从中选择一个随机类型。
我打算使用 arc4random() % 4
来完成它,只是在它的位置使用 int 但想检查是否有更好的方法来做到这一点。
最佳答案
typedef enum {
FirstType = 0,
SecondType,
ThirdType,
EnumTypeMax
} EnumType;
EnumType randomType = (EnumType) (arc4random() % (int) EnumTypeMax);
请注意 EnumTypeMax
等于 3
,而不是 4
,这是正确的。
EnumTypeMax
被认为是无效值。
另请参阅我的回答 here关于 X-Macros 解决方案。
关于iphone - 在 Objective-C 中选择一个随机枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688639/