PART_A 枚举简介
定义:一组相关的值定义了一个共同的枚举类型
语法格式 enum Direction {
case East
case South
case West
case North
case NorthWest,EastSouth
}
类型推断 var currentDirection = Direction.East
currentDirection =.South
使用Switch匹配枚举值
switch需要穷举枚举成员,可以使用default分支来涵盖所有未明确处理的枚举成员 var currentDirection = Direction.East
switch currentDirection {
case .East:
print("East")
case .South:
print("South")
case .West:
print("West")
case .North:
print("North")
case .NorthWest,.EastSouth:
print("Other")
default:
print("Default")
}
PART_B 关联值
定义:将枚举成员使用元组组合成关联值
注意:同一变量可被分配成不同类型的关联值,但同一时刻仅能存储为一种类型
语法格式 enum Person {
case Male(String,Int)
case Female(String,String)
}
func test() {
var p1 = Person.Male("zhangsan",28)
switch p1 {
case .Male(let name,let age):
print("(name),(age)")
case let .Female(name,desc):
print("(name),(desc)")
}
}
PART_C1 原始值:原始值的类型必须相同
定义:即默认值. 对于一个特定的枚举成员,其原始值始终不变
说明
语法格式 enum OriginStr: String {
case str1 = "hi"
case str2 = "how are you"
}
PART_C2 原始值的隐式赋值
当使用整数作为原始值,隐式赋值依次递增1. 若第一个枚举成员未设置原始值,默认为0
当使用字符串作为原始值,每个枚举成员的隐式原始值为该枚举成员的名称
enum Planet: Int {
case Mercury = 1,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune
}
enum CompassPoint: String {
case North,South,East,West
}
let earthsOrder = Planet.Earth.rawValue
使用原始值初始化枚举实例 let possiblePlanet = Planet(rawValue: 7)
PART_D 递归枚举(indirect ):情况可被穷举时,适合数据建模
以下为解决案例:(3 + 4) * 5
定义
方式一 enum ArithmeticExpression {
case Num(Int)
indirect case Add(ArithmeticExpression,ArithmeticExpression)
indirect case Multiple(ArithmeticExpression,ArithmeticExpression)
}
方式二:所有成员可递归时,将 indirect 放在 enum 声明前 indirect enum ArithmeticExpression2 {
case Num(Int)
case Add(ArithmeticExpression,ArithmeticExpression)
case Multiple(ArithmeticExpression,ArithmeticExpression)
}
func test(expression: ArithmeticExpression) -> Int {
switch expression {
case let .Num(value):
return value
case let .Add(a,b):
return test11(a) + test11(b)
case let .Multiple(a,b):
return test11(a) * test11(b)
}
} // 调用运算方法、递归枚举进行运算
let three = ArithmeticExpression.Num(3)
let four = ArithmeticExpression.Num(4)
let sum = ArithmeticExpression.Add(three,four)
let result = ArithmeticExpression.Multiple(sum,ArithmeticExpression.Num(5))
以上。如有错误和疑问,欢迎指正提出。 catface.wyh@gmail.com
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|