Swift:选择随机枚举值

前端之家收集整理的这篇文章主要介绍了Swift:选择随机枚举值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图随机选择枚举值,这是我目前的尝试:
  1. enum GeometryClassification {
  2.  
  3. case Circle
  4. case Square
  5. case Triangle
  6. case GeometryClassificationMax
  7.  
  8. }

随机选择:

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

然而,这却失败了.

我收到错误,如:

  1. 'GeometryClassification' is not convertible to 'UInt32'

任何想法如何解决

我不会对你最后一次的情况感到疯狂 – 看起来你正在包括.GeometryClassificationMax,只允许随机选择.您需要在每个使用switch语句的地方考虑到额外的情况,并且它没有语义值.相反,枚举上的静态方法可以确定最大值并返回一个随机的情况,并且会更容易理解和维护.
  1. enum GeometryClassification: UInt32 {
  2. case Circle
  3. case Square
  4. case Triangle
  5.  
  6. private static let _count: GeometryClassification.RawValue = {
  7. // find the maximum enum value
  8. var maxValue: UInt32 = 0
  9. while let _ = GeometryClassification(rawValue: maxValue) {
  10. maxValue += 1
  11. }
  12. return maxValue
  13. }()
  14.  
  15. static func randomGeometry() -> GeometryClassification {
  16. // pick and return a new value
  17. let rand = arc4random_uniform(_count)
  18. return GeometryClassification(rawValue: rand)!
  19. }
  20. }

现在,您可以在switch语句中使用枚举:

  1. switch GeometryClassification.randomGeometry() {
  2. case .Circle:
  3. println("Circle")
  4. case .Square:
  5. println("Square")
  6. case .Triangle:
  7. println("Triangle")
  8. }

猜你在找的Swift相关文章