i am trying to randomly chose a enum value, this is my current attempt:
enum GeometryClassification {
case Circle
case Square
case Triangle
case GeometryClassificationMax
}
and the random selection:
let shapeGeometry = ( arc4random() % GeometryClassification.GeometryClassificationMax ) as GeometryClassification
this however fails miserably.
i get errors like:
'GeometryClassification' is not convertible to 'UInt32'
any ideas on how to solve that?
Swift has gained new features since this answer was written that provide a much better solution — see this answer instead.
I'm not crazy about your last case there -- it seems like you're including
.GeometryClassificationMax
solely to enable random selection. You'll need to account for that extra case everywhere you use aswitch
statement, and it has no semantic value. Instead, a static method on theenum
could determine the maximum value and return a random case, and would be much more understandable and maintainable.And you can now exhaust the
enum
in aswitch
statement:In Swift there is actually a protocol for enums called
CaseIterable
that, if you add it to your enum, you can just reference all of the cases as a collection with.allCases
as so:and then you can
.allCases
and then.randomElement()
to get a random oneThe force unwrapping is required because there is a possibility of an enum having no cases and thus
randomElement()
would returnnil
.Here's my Swift 1.2 take:
Since you're inside the enum class, having the random() method reference the highest value explicitly would eliminate having to count them every time:
You need to assign a raw type to your enum. If you use an integer type, then the enumeration case values will be auto-generated starting at 0:
"Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created." - as per this page. Specifying the integer type lets it know to generate the values in the usual way.
Then you can generate the random value like this:
This is a horribly ugly call, and all those 'fromRaw' and 'toRaw' calls are fairly inelegant, so I would really recommend generating a random UInt32 that is in the range you want first, then creating a GeometryClassification from that value:
You can put all the values into array and generate random,