Sebastian Flückiger Sebastian Flückiger - 1 year ago 582
Swift Question

Swift: Chose a random enumeration value

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?

Answer Source

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 a switch statement, and it has no semantic value. Instead, a static method on the enum could determine the maximum value and return a random case, and would be much more understandable and maintainable.

enum GeometryClassification: UInt32 {
    case Circle
    case Square
    case Triangle

    private static let _count: GeometryClassification.RawValue = {
        // find the maximum enum value
        var maxValue: UInt32 = 0
        while let _ = GeometryClassification(rawValue: maxValue) { 
            maxValue += 1
        return maxValue

    static func randomGeometry() -> GeometryClassification {
        // pick and return a new value
        let rand = arc4random_uniform(_count)
        return GeometryClassification(rawValue: rand)!

And you can now exhaust the enum in a switch statement:

switch GeometryClassification.randomGeometry() {
case .Circle:
case .Square:
case .Triangle:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download