How to choose a random enumeration value

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.

Leave a Comment