I am trying to randomly choose an enum value:
enum GeometryClassification { case Circle case Square case Triangle case GeometryClassificationMax }
and the random selection:
let shapeGeometry = ( arc4random() % GeometryClassification.GeometryClassificationMax ) as GeometryClassification
but it fails.
I get errors like:
'GeometryClassification' is not convertible to 'UInt32'
How do I solve this?
This method use the java. util. Random to create a random value. This random value then will be used to pick a random value from the enum.
An enumeration is a data type that consists of a set of named values that represent integral constants, known as enumeration constants. An enumeration is also referred to as an enumerated type because you must list (enumerate) each of the values in creating a name for each of them.
On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.
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:
enum GeometryClassification: CaseIterable { case Circle case Square case Triangle }
and then you can .allCases
and then .randomElement()
to get a random one
let randomGeometry = GeometryClassification.allCases.randomElement()!
The force unwrapping is required because there is a possibility of an enum having no cases and thus randomElement()
would return nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With