You can define Swift enumerations to store associated values of any given type, and the value types can be different for each case of the enumeration if needed.
enum Barcode { case upc(Int, Int, Int, Int) // tuple 类型 case qrCode(String) // String 类型 } // switch 匹配 switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: /(numberSystem), /(manufacturer), /(product), /(check).") case .qrCode(let productCode): print("QR code: /(productCode).") } // 如果全部是 let 或 var 时,还可以将 let 或 var 提到前面 switch productBarcode { case let .upc(numberSystem, manufacturer, product, check): print("UPC : /(numberSystem), /(manufacturer), /(product), /(check).") case let .qrCode(productCode): print("QR code: /(productCode).") }
enum ASCIIControlCharacter: Character { case tab = "/t" case lineFeed = "/n" case carriageReturn = "/r" }
Raw values are not the same as associated values. Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration’s cases, and can be different each time you do so.
// 整型的原始值是指定值后续递增,不指定从 0 开始 enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } // 字符串的原始值为 case 名字 enum CompassPoint: String { case north, south, east, west } // 原始可以通过 rawValue 属性直接获取,如果不定义为 Raw Values 类型的 enum 是没有 rawValue 属性的 let earthsOrder = Planet.earth.rawValue // earthsOrder is 3 let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west"
let possiblePlanet = Planet(rawValue: 7) // possiblePlanet is of type Planet? and equals Planet.uranus
The raw value initializer is a failable initializer, because not every raw value will return an enumeration case.
enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) indirect case multiplication(ArithmeticExpression, ArithmeticExpression) } indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(ArithmeticExpression, ArithmeticExpression) } func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression { case let .number(value): return value case let .addition(left, right): return evaluate(left) + evaluate(right) case let .multiplication(left, right): return evaluate(left) * evaluate(right) } } print(evaluate(product))
P.S. 这篇 blog 还有很多 Enum 的其他用法: https://appventure.me/2015/10/17/advanced-practical-enum-examples/