3

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.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306

1 Answers1

19
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.

Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Perfect, thanks. Was just going to confirm that LastType never gets chosen but you've just confirmed that for me :D Plus tested and it works. Thanks... Will accept when the timer runs out. – Fogmeister Oct 02 '12 at 10:37
  • 1
    Renamed `LastType` to `EnumTypeMax`. – Sulthan Oct 02 '12 at 11:09
  • 3
    In iOS 4.3 and above you should use `arc4random_uniform(EnumTypeMax)` rather than `arc4random() % EnumTypeMax` – g_fred Oct 02 '12 at 11:15