Enum: A group of related values that define a common type, allowing you to use these values in your code in a type-safe manner.
1. Enumeration syntax
//枚举成员不会被赋予默认的整型值。成员本身就是完备的值,类型为CompassPoint。
enum CompassPoint {
case north
case south
case east
case west
}
//或者
enum Planet {
case mercury, venus, earth
}
2. The use of enumeration
var direction = CompassPoint.west
//direction: 已被推断类型,所以下次给他赋值的时候:
direction = .east
3. Use the Switch statement to match the enumeration value
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. Traversal of enumeration members
enum CompassPoint: CaseIterable {
// CaseIterable : 协议
case coffee, tea, juice
}
let number = CompassPoint.allCases.count
// allCases:包含所有枚举成员的集合方法
print("\(number)")
//或者
for com in CompassPoint.allCases{
print(com)
}
5. Associated value
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. Raw value
Raw value: The value that was pre-populated when the enum was defined.
enum ASCIICharacter: Character {
case tab = "\t"
case lineFeed = "\h"
case carriageReturn = "\r"
}
7. Implicit assignment of primitive values
(1) When the integer is the original value, the implicit assignment increments by 1. When the original value is not set, it defaults to 0 and increments by 1 thereafter.
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) The string is the original value, and the implicit assignment is the name of the enumeration member.
enum CompassPoint: String {
case north, south, east, west //他们的原始值为"north", "south", "east", "west"
}
8. Initialize the enumeration instance with the original value
let poss = Planet(rawValue: 7)
//poss:返回名称。如果没有则返回nil。 7:要查找的值。
9. Recursive enumeration
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))