Z
ZHANK
编程在线教程Swift 教程枚举与模式匹配深入
现代 Swift

枚举与模式匹配深入

关联值/原始值枚举、递归枚举 indirect、Result 就是枚举

枚举与模式匹配深入

Swift 枚举超越 C 的整数枚举——关联值携带数据,indirect 支持递归,Result 就是枚举。

学完本章你将: 掌握关联值/原始值、递归枚举 indirect、枚举方法。


关联值

swift
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var code = Barcode.upc(8, 85909, 51226, 3)
code = .qrCode("https://example.com")

switch code {
case .upc(let a, let b, let c, let d):
    print("UPC: \(a)\(b)\(c)\(d)")
case .qrCode(let url):
    print("QR: \(url)")
}

原始值

swift
enum Planet: Int, CaseIterable {  // CaseIterable = 可遍历
    case mercury = 1, venus, earth, mars
}

Planet.earth.rawValue  // 3
Planet(rawValue: 2)     // Optional(.venus)
Planet.allCases         // [mercury, venus, earth, mars]

递归枚举 indirect

swift
indirect enum List {
    case empty
    case node(Int, List)  // 递归——List 包含 List
}

let list = List.node(1, .node(2, .node(3, .empty)))

func printList(_ list: List) {
    switch list {
    case .empty: break
    case .node(let value, let next):
        print(value)
        printList(next)
    }
}