【问题标题】:Choosing a random enum in Objective-C在 Objective-C 中选择一个随机枚举
【发布时间】:2012-10-02 10:28:35
【问题描述】:

我已经为我的 iPhone 应用程序创建了一个 typedef 枚举...

typedef enum {
    FirstType,
    SecondType,
    ThirdType
} type;

只是为了测试,我希望能够从这些中选择一个随机类型。

我打算使用 arc4random() % 4 来做这件事,只是用 int 代替它,但想检查是否有更好的方法。

【问题讨论】:

    标签: iphone ios enums typedef


    【解决方案1】:
    typedef enum {
        FirstType = 0,
        SecondType,
        ThirdType,
        EnumTypeMax
    } EnumType;
    
    EnumType randomType = (EnumType) (arc4random() % (int) EnumTypeMax);
    

    注意EnumTypeMax 等于3,而不是4,这是正确的。 EnumTypeMax 被认为是无效值。

    另外,请参阅我关于 X-Macros 解决方案的回答 here。

    【讨论】:

    • 完美,谢谢。只是要确认 LastType 永远不会被选中,但您刚刚确认对我来说 :D Plus 经过测试并且它有效。谢谢...当计时器用完时会接受。
    • 将LastType 重命名为EnumTypeMax。
    • 在 iOS 4.3 及更高版本中你应该使用arc4random_uniform(EnumTypeMax) 而不是arc4random() % EnumTypeMax
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 2014-08-06
    • 2016-05-18
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多