Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose a random enumeration value

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?

like image 528
Sebastian Flückiger Avatar asked Oct 08 '14 15:10

Sebastian Flückiger


People also ask

How do you choose a random value for an enum?

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.

What are enumeration values?

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.

What is the size of an enumeration type?

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.


1 Answers

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.

like image 132
Pharphuf7nik Avatar answered Oct 12 '22 19:10

Pharphuf7nik