我试图随机选择枚举值,这是我目前的尝试:
- 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")
- }