美文网首页
Swift9 - 枚举

Swift9 - 枚举

作者: 暗物质 | 来源:发表于2020-06-09 11:11 被阅读0次
    //#  枚举成员的遍历
    enum Beverage: CaseIterable {
        case coffee, tea, juice
    }
    
    let numberOfChoices = Beverage.allCases.count
    print("\(numberOfChoices) beverages available")
    // 打印“3 beverages available”
    for beverage in Beverage.allCases {
        print(beverage)
    }
    
    // 定义表示两种商品条形码的枚举:
    enum Barcode {
        case upc(Int, Int, Int, Int)
        case qrCode(String)
    }
    
    var productBarcode = Barcode.upc(8, 85999, 55564, 3)
    productBarcode = Barcode.qrCode("ABCDEFGHIJKLMN")
    
    switch productBarcode {
        case let .upc(numberSystem, manufacturer, product, check):
            print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
        case let .qrCode(productCode):
        print("QR code: \(productCode).")
    }
    
    
    //## 原始值 rawValue
    //原始值始终不变。关联值是创建一个基于枚举成员的常量或变量时才设置的值,枚举成员的关联值可以变化。
    enum Planet: Int {
        case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
    }
    enum CompassPoint: String {
        case north, south, east, west
    }
    
    let positionToFind = 11
    if let somePlanet = Planet(rawValue: positionToFind) {
        switch somePlanet {
        case .earth:
            print("Mostly harmless")
        default:
            print("Not a safe place for humans")
        }
    }else {
        print("There isn't a planet at position \(positionToFind)")
    }
    
    //可以在枚举成员前加上 indirect 来表示该成员可递归。
    

    相关文章

      网友评论

          本文标题:Swift9 - 枚举

          本文链接:https://www.haomeiwen.com/subject/cttszhtx.html