简体   繁体   中英

Choosing a random enum in Objective-C

I've created a typedef enum for my iPhone app...

typedef enum {
    FirstType,
    SecondType,
    ThirdType
} type;

Just for testing I'd like to be able to pick a random type from these.

I was going to use arc4random() % 4 to do it and just use the int in its place but wanted to check if there was a better way of doing this.

typedef enum {
    FirstType = 0,
    SecondType,
    ThirdType,
    EnumTypeMax
} EnumType;

EnumType randomType = (EnumType) (arc4random() % (int) EnumTypeMax);

Note that EnumTypeMax is equal to 3 , not 4 and that is correct. EnumTypeMax is considered to be an invalid value.

Also, see my answer here about an X-Macros solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM