Swift:选择随机枚举值

Swift:选择随机枚举值,第1张

概述我试图随机选择枚举值,这是我目前的尝试: enum GeometryClassification { case Circle case Square case Triangle case GeometryClassificationMax} 和随机选择: let shapeGeometry = ( arc4random() % GeometryClassifi 我试图随机选择枚举值,这是我目前的尝试:
enum GeometryClassification {    case Circle    case Square    case Triangle    case GeometryClassificationMax}

和随机选择:

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

然而,这却失败了.

我收到错误,如:

'GeometryClassification' is not convertible to 'UInt32'

任何想法如何解决?

我不会对你最后一次的情况感到疯狂 – 看起来你正在包括.GeometryClassificationMax,只允许随机选择.您需要在每个使用switch语句的地方考虑到额外的情况,并且它没有语义值.相反,枚举上的静态方法可以确定最大值并返回一个随机的情况,并且会更容易理解和维护.
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语句中使用枚举:

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

以上是内存溢出为你收集整理的Swift:选择随机枚举值全部内容,希望文章能够帮你解决Swift:选择随机枚举值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1038898.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存