枚举:一组相关的值定义了一个共同的类型,使你可以在代码中以类型安全的方式来使用这些值。
1.枚举语法
//枚举成员不会被赋予默认的整型值。成员本身就是完备的值,类型为CompassPoint。
enum CompassPoint {
case north
case south
case east
case west
}
//或者
enum Planet {
case mercury, venus, earth
}
2.枚举的使用
var direction = CompassPoint.west
//direction: 已被推断类型,所以下次给他赋值的时候:
direction = .east
3.使用Switch语句匹配枚举值
direction = .south
switch direction {
case .north:
print("north")
case .south:
print("south")
case .east:
print("east")
case .west:
print("west")
}
//强调判断枚举的全部成员,如果没有判断全部成员则报错。所以在不需要判断全部成员时使用default。
switch direction {
case .north:
print("north")
default:
print("其他")
}
4.枚举成员的遍历
enum CompassPoint: CaseIterable {
// CaseIterable : 协议
case coffee, tea, juice
}
let number = CompassPoint.allCases.count
// allCases:包含所有枚举成员的集合方法
print("\(number)")
//或者
for com in CompassPoint.allCases{
print(com)
}
5.关联值
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var product = Barcode.upc(8, 85909, 51226, 3)
product = .qrCode("ABCDEFG")
switch product {
case .upc(let n, let m, let p, let c):
print("upc:\(n), \(m), \(p), \(c)")
case .qrCode(let pc):
print("QR code:\(pc).")
}
//简洁后:
switch product {
case let .upc(n, m, p, c):
print("upc:\(n), \(m), \(p), \(c)")
case let .qrCode(pc):
print("QR code:\(pc).")
}
6.原始值
原始值:定义枚举时被预先填充的值。
enum ASCIICharacter: Character {
case tab = "\t"
case lineFeed = "\h"
case carriageReturn = "\r"
}
7.原始值的隐式赋值
(1)整数为原始值时,隐式赋值递增1。未设置原始值时,默认为0,之后递增1.
enum Planet: Int {
case m = 1, n, r, j //只为m赋原始值1
}
var x = Planet.n //创建枚举变量x, x的值为n
var y = x.rawValue //通过rawValue属性来获取枚举的原始值
print(y) //y的值为2
(2)字符串为原始值,隐式赋值为枚举成员的名称。
enum CompassPoint: String {
case north, south, east, west //他们的原始值为"north", "south", "east", "west"
}
8.使用原始值初始化枚举实例
let poss = Planet(rawValue: 7)
//poss:返回名称。如果没有则返回nil。 7:要查找的值。
9.递归枚举
enum Arith {
case number(Int)
indirect case add(Arith, Arith) //indirect :可递归
indirect case mul(Arith, Arith)
}
//简化
indirect enum Arith { //indirect :所有成员可递归
case number(Int)
case add(Arith, Arith)
case mul(Arith, Arith)
}
//使用
let five = Arith.number(5)
let four = Arith.number(4)
let sum = Arith.add(five, four)
let product = Arith.mul(sum, Arith.number(2))