Swift 里枚举翻身了,和类、结构体可以并列了,地位很高啦
//简单定义一个方向枚举, 也是用驼峰法命名, 枚举一般使用单数形式
enum CompassDirection {
case north //单个成员值不用加“,”
case south
case west, east //多个成员值可以写在一行里,用“,”隔开
}
//匹配枚举
let direction = CompassDirection.west
switch direction {
case .north:
print("North")
case .south:
print("South")
case .west:
print("west")
case .east:
print("east")
}
这个貌似是新特性,我在老版本不支持这个协议呢。。
//枚举可以遵循一个CaseIteralble,就可以访问枚举的所有类型的集合
//enum EarthPlant : CaseIteralble {
// case muxing, huoxing, tuxing, shuixng
// case tianwangxing
// case xiaoxingxing
//}
//let allCase = EarthPlant.allCases
//枚举关联值
enum BarCode {
case lineCode(Int, Int, Int, Int) //条形码, 存储四个数字
case qrCode(String) //二维码 存储一个字符串
}
//关联值直接使用
var code = BarCode.lineCode(3, 10256, 36526, 6)
code = BarCode.qrCode("ThisISTwoCode")
switch code {
case .lineCode(let firstNum, let SecondNum, let ThirdNum, let ForthNum):
print("nums 1-4: \(firstNum, SecondNum, ThirdNum, ForthNum)")
case .qrCode(let erCode):
print("qrCode = \(erCode)") //qrCode = ThisISTwoCode
}
//指定原始值
enum TableChart: String {
case tab = "\t"
case line = "\n"
case kong = " "
}
print(TableChart.kong.rawValue)
//预设原始值 Int类型 顺序赋值
enum Plant : Int {
case earth = 1, tuxing, muxing, shuixing, huoxing
}
print(Plant.muxing.rawValue) //3
let xing = Plant(rawValue: 5)
print(xing) // Optional(__lldb_expr_75.Plant.huoxing)
枚举递归的使用:
//递归枚举 枚举前面要加 indirect
indirect enum CustomFunction {
case num(Int) //一个数字
case addFunction(CustomFunction, CustomFunction) //加法公示 两个数字
case mutilpleFunc(CustomFunction, CustomFunction) //乘法
}
//5 + 4 * 2
let num1 = CustomFunction.num(5)
let num2 = CustomFunction.num(4)
let num3 = CustomFunction.num(2)
let addExpretion = CustomFunction.addFunction(num1, num2)
let mupleExpretion = CustomFunction.mutilpleFunc(addExpretion, num3)
print(mupleExpretion) //mutilpleFunc(__lldb_expr_130.CustomFunction.addFunction(__lldb_expr_130.CustomFunction.num(5), __lldb_expr_130.CustomFunction.num(4)), __lldb_expr_130.CustomFunction.num(2))
func eval(_ expression: CustomFunction) -> Int {
switch expression {
case .num(let value):
return value
case .addFunction(let first, let second):
return eval(first) + eval(second)
case .mutilpleFunc(let first, let second):
return eval(first) * eval(second)
}
}
print(eval(mupleExpretion)) // 18
以上的打印结果: