如何选择随机枚举值 [英] How to choose a random enumeration value

查看:92
本文介绍了如何选择随机枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试随机选择一个枚举值:

I am trying to randomly choose an enum value:

enum GeometryClassification {

    case Circle
    case Square
    case Triangle
    case GeometryClassificationMax

}

和随机选择:

let shapeGeometry = ( arc4random() % GeometryClassification.GeometryClassificationMax ) as GeometryClassification

但失败.

我收到如下错误:

'GeometryClassification' is not convertible to 'UInt32'

我该如何解决?

推荐答案

自从编写此答案以来,Swift获得了许多新功能,它们提供了更好的解决方案-请参阅"

Swift has gained new features since this answer was written that provide a much better solution — see "How to choose a random enumeration value" instead.

对于您的最后一种情况,我并不感到疯狂-似乎您包括.GeometryClassificationMax只是为了启用随机选择.在使用switch语句的任何地方,都需要考虑到这种额外的情况,并且该语句没有语义值.取而代之的是,enum上的静态方法可以确定最大值并返回随机情况,这将更加易于理解和维护.

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)!
    }
}

现在您可以在switch语句中用尽enum:

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

switch GeometryClassification.randomGeometry() {
case .Circle:
    println("Circle")
case .Square:
    println("Square")
case .Triangle:
    println("Triangle")
}

这篇关于如何选择随机枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆