Swift中的枚举

1. 枚举的关联值

enum BarCode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
// 输出 "QR code: ABCDEFGHIJKLMNOP.
// case let .upc(numberSystem, manufacturer, product, check) 等同于 case .upc(let numberSystem, let manufacturer, let product, let check)

2. 原始值

enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

2.1 原始值的隐式赋值

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

在上面的例子中,Plant.mercury的显式原始值为1,Planet.venus的隐式原始值为2,依次类推。

enum CompassPoint: String {
    case north, south, east, west
}

let sunsetDirection = CompassPoint.west.rawValue
print(sunsetDirection)
// print "west\n"

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

enum Planet:Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet = uranus

注意:
原始值构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的枚举成员。

if let positionToFind = Planet(rawValue: 11) {
    print(positionToFind)
} else {
    print("no position")
}
// print "no position\n"

你可能感兴趣的:(Swift中的枚举)