iphone - 在 Objective-C 中选择一个随机枚举

标签 iphone ios enums typedef

我已经为我的 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/

相关文章:

ios - 当我为 iOS 编译某些东西时,使用了哪些架构?

IOS UIButton 不响应触摸,需要多次按下,UIScreenEdge 手势干扰?

ios - 保存 UIScrollView 位置并在应用程序再次打开时恢复。 ( objective-C )

javascript - 在我的 iPhone 应用程序中执行 JavaScript

c - C 中的枚举不会在无效输入时引发错误

iphone - 无法在 iOS 5.0 中调整事件指示器的大小?

iphone - Phonegap iOS 应用程序屏幕在双击时向上滑动

ios - Iphone X 屏幕未覆盖 cordova 项目中的页眉和页脚

enums - 我可以限制 Rust 枚举的大小吗?

c - 在函数 c 中使用枚举定义全局变量