Swift里面的枚举和C,OC里面的最大区别是多了一个case.
enum SomeEnumeration { // enumeration definition goes here }
// 例子1 enum CompassPoint{ case North case South case East case West } var directionToHead = CompassPoint.West // 第一次声明一个变量的时候需要加上枚举名 directionToHead = .South // 第二次可以直接使用.操作 switch directionToHead { case .North: print("Lots of planets have a north") case .South: print("Watch out for penguins") case .East: print("Where the sun rises") case .West: print("Where the skies are blue") } // 在上面的例子中枚举CompassPoint并没有明确的数据类型,所以枚举也没有默认值 0 1 2 3 // 例子2 // 枚举的多个case可以写在一行,中间使用","分割开 enum Planet { case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }
苹果使用的是二维码和条形码的例子.
// 例子3 enum Barcode { case UPCA(Int, Int, Int, Int) //条形码 case QRCode(String) // 二维码 } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) // 给一个变量赋值 //productBarcode = .QRCode("ABCDEFGHIJKLMNOP") switch productBarcode { case let .UPCA(numberSystem, manufacturer, product, check): print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).") case let .QRCode(productCode): print("QR code: \(productCode).") }在上面的例子中,都没有初始值和类型.
// 例子4 (给上面的例子2 增加了数据类型和初始值) enum Planet1: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } // 打印Raw Values print("Venus.rawValue: \(Planet1.Venus.rawValue).") //Venus.rawValue: 2. // 如果我们不做 Mercury = 1 的操作那么上面的打印结果是:Venus.rawValue: 1. // 也就是说,我们在给一个枚举设置类型的时候,Swift会给我们一个默认初始值 Int类型的是从0开始 // 获取raw value 是7的枚举 let possiblePlanet = Planet1(rawValue: 7) print("possiblePlanet: \(possiblePlanet)")
enum ArithmeticExpression { case Number(Int) indirect case Addition(ArithmeticExpression, ArithmeticExpression) indirect case Multiplication(ArithmeticExpression, ArithmeticExpression) }或者加上 indirect
indirect enum ArithmeticExpression { case Number(Int) case Addition(ArithmeticExpression, ArithmeticExpression) case Multiplication(ArithmeticExpression, ArithmeticExpression) }
func evaluate(expression: ArithmeticExpression) -> Int { switch expression { case .Number(let value): return value case .Addition(let left, let right): return evaluate(left) + evaluate(right) case .Multiplication(let left, let right): return evaluate(left) * evaluate(right) } } // evaluate (5 + 4) * 2 let five = ArithmeticExpression.Number(5) let four = ArithmeticExpression.Number(4) let sum = ArithmeticExpression.Addition(five, four) let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2)) print(evaluate(product)) // Prints "18"