【发布时间】:2012-10-02 10:28:35
【问题描述】:
我已经为我的 iPhone 应用程序创建了一个 typedef 枚举...
typedef enum {
FirstType,
SecondType,
ThirdType
} type;
只是为了测试,我希望能够从这些中选择一个随机类型。
我打算使用 arc4random() % 4 来做这件事,只是用 int 代替它,但想检查是否有更好的方法。
【问题讨论】:
我已经为我的 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 被认为是无效值。
另外,请参阅我关于 X-Macros 解决方案的回答 here。
【讨论】:
LastType 重命名为EnumTypeMax。
arc4random_uniform(EnumTypeMax) 而不是arc4random() % EnumTypeMax