<Swift 巩固笔记> 第8篇 枚举

312 阅读2分钟

枚举语法

enum CompassPoint {
    // Swift中的枚举成员在被创建时不会被赋予一个默认的整型值
    case north // 这就是成员值
    case south
    case east
    case west
}

在同一行定义枚举成员, 用逗号隔开

enum Planet {
    // 水星, 金星, 地球, 火星, 木星, 土星, 天王星, 海王星
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

// 枚举类型的使用
var direction = CompassPoint.north

// 当我们知道一个变量为枚举类型, 我们还可以这样简单的使用
direction = .south

枚举值的匹配

强制穷举, 否则编译不通过

switch direction {
case .north:
    print("this is north direction")
case .south:
    print("this is south direction")
case .east:
    print("this is east direction")
case .west:
    print("this is west direction")
}

使用使用default语句时, 就不必穷举了

switch direction {
case .north:
    print("north is my favourite direction")
default:
    print("I don't like other direction")
}

枚举成员的遍历

enum Beverage: CaseIterable {
    case coffee, tea, juice
}

// 遵循CaseIterablell协议的枚举
print(Beverage.allCases.count)

// 遍历所有的枚举成员
for value in Beverage.allCases {
    print(value)
}

关联值

/**
 把其它类型的值和成员值一起存储起来会很有用, 这个额外的信息就是关联值
 */
enum Barcode {
    case upc(Int, Int, Int, Int) // 关联值的类型是 (Int, Int, Int, Int)
    case qrCode(String) // 关系值的类型是 (String)
}

var productBarcode  = Barcode.upc(8, 88888, 66666, 3)
print(productBarcode)

productBarcode = Barcode.qrCode("thisisgood")
print(productBarcode)

用Switch检查不同条形码类型

switch productBarcode {
//    case .upc(let systemNumber, let manufacturer, let product, let check):
//    case var .upc(systemNumber, manufacturer, product, check): // 也可以这样
case let .upc(systemNumber, manufacturer, product, check): // 也可以这样
    print("UPC: \(systemNumber) - \(manufacturer) - \(product) - \(check)")
    
case .qrCode(let code):
    print("QR code: \(code)")
}

原始值 / 默认值

/**
 原始值是是在定义枚举时必须填充的值
 原始值的类型必须相同
 对于一个特定的枚举成员, 它的原始值始终不变
 */
enum ASCIIControlCharacter: Character, CaseIterable {
    case tab = "\t" // 制表
    case lineFeed = "\n" // 换行
    case carriageReturn = "\r" // 回车
}

var c = ASCIIControlCharacter.tab

原始值的隐式赋值

/**
 当使用整数作为原始值时, 隐式赋值的值依次递增1, 默认原始值为0
 */
enum Star: Int {
    // 水星, 金星, 地球, 火星, 木星, 土星, 天王星, 海王星
    // meycury的显式原始值为1, 那么vernus的隐式原始值为2, 依此类推
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// 枚举成员的rawValue属性访问原始值
let starValue = Star.earth.rawValue

// starValue 隐式类型: Int
print(starValue)

/**
 当使用字符串作为枚举类型的原始值时, 每个枚举成员的隐式原始值为该枚举成员的名称
 */
enum Compass: String {
    case north
    case south
    case east
    case west
}

let directionValue = Compass.south.rawValue

// directionValue 隐式类型: String
print(directionValue)

使用原始值初始化枚举实例

// possibleStar的类型为 Star?, 也就是可选的类型
// 并非所有的Int值都可以找到一个匹配的行星
let possibleStar = Star(rawValue: 10);
if let someStar = possibleStar {
    print(someStar)
} else {
    print("There isn't a star")
}

递归枚举 - 暂时想不到应用场景