为什么要先介绍类和结构体再介绍枚举呢。我觉得枚举是类的特殊存在形式。因为类完全可以替代枚举。不过swift中也有许多类的特性被枚举支持。这个后面学习到特性的时候自然就知道了。
1、什么是枚举
枚举定义了一个通用类型的一组相关值,使你可以在你的代码中以一种安全的方式来使用这些值。 - 太抽象了。
2、定义以及使用
enum CompassPoint {
case North
case South
case East
case West
}
//或者
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}//或者
enum CompassPoint {
case North(Int,Int)
case South
case East
case West
}
//或者 设置隐式赋值,第一个不设置则从0开始,设置则从设置的值开始隐式递增
enum CompassPoint : Int{
case North = 1
case South
case East
case West
}
enum关键字表示定义枚举,case表示定义一行成员,定义完成之后,其实CompassPoint 的 North并不会赋值0,可以理解为每一个成员都拥有不同的类型。就是它自己。
//使用
var directionToHead = CompassPoint.West
//修改它的值,在directionToHead类型已知的情况下表,可以把枚举名称省略,不过不推荐这样做。
directionToHead = .East
//switch判断,可以理解为判断directionToHead的值是.North则打印"Lots of planets have a north"
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")
}
这样判断必须穷举所有成员,否则就需要增加default这个选项了。不过谁这样用呢。
//成员递归
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
//枚举递归
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)
}
}
// 计算 (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))
// 输出 "18"