Swift 枚举Enumerations
发布时间:2020-12-14 07:17:19 所属栏目:百科 来源:网络整理
导读:Swift里面的枚举和C,OC里面的最大区别是多了一个case. 枚举表达式 enum SomeEnumeration { // enumeration definition goes here} 没有初始值和类型 // 例子1enum CompassPoint{ case North case South case East case West}var directionToHead = CompassPo
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) //条形码 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,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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |