【代码演示】 import UIKit//1、枚举语法
enum CompassPoint {case northcase southcase esatcase west
}enum Planet {case merury,veus,earth,mars,jupiter,saturn,uranus,neptune
}//2、switch 语句匹配枚举值let directionToHead = CompassPoint.southswitch directionToHead {
case .north:print("north...")
case .south:print("south")//结果:south
case .esat:print("east")
case .west:print("west")
}//3、遍历enum Colors:CaseIterable {case yellowcase graycase redcase blackcase white
}let colorsOfCount = Colors.allCases.count
print("colors.count \(colorsOfCount)")//结果:colors.count 5for color in Colors.allCases{
print(color)//结果:yellow gray red black white
}
//4、关联值
enum Barcode {case upc(Int,Int,Int,Int)case qrCode(String)
}var productBarcode = Barcode.upc(8, 55909, 51226, 3)
print(productBarcode)//结果:upc(8, 55909, 51226, 3)
productBarcode = .qrCode("ABCDFET")
print(productBarcode)//结果:qrCode("ABCDFET")switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product,let check):print("UPC:\(numberSystem),\(manufacturer),\(product),\(check)")
case .qrCode(let productCode):print("QR code:\(productCode)")//结果:QR code:ABCDFET
}//5、原始值
enum ASSCIIControlCharacter:Character {case tab = "\t"case lineFeed = "\n"case carriageRetunr = "r"
}//6、预设原始值
enum names:String {case zhangsan,lisi,wangwu,zhaoliu
}enum age:Int {case zhangsan = 23,lisi,wangwu,zhaoliu
}
//7、递归枚举
indirect enum ArithmeticExpression {case number(Int)case add(ArithmeticExpression,ArithmeticExpression)case mutiply(ArithmeticExpression,ArithmeticExpression)
}let firstExpression = ArithmeticExpression.number(5)
let secondExpression = ArithmeticExpression.number(4)
let addExpression = ArithmeticExpression.add(firstExpression, secondExpression)
let thirdExpression = ArithmeticExpression.number(2)
let mutiplyExpression =
ArithmeticExpression.mutiply(addExpression, thirdExpression)
print(mutiplyExpression)func eval(_ expresson:ArithmeticExpression) ->Int{switch expresson {case .number(let value):return valuecase .add(let num1, let num2):return eval(num1) + eval(num2)case .mutiply(let num1, let num2):return eval(num1) * eval(num2)}}print(eval(mutiplyExpression))