enum CompassPoint {
case North
case South
case East
case West
}
enum CompassPoint {
case North, South, East, West
}
上例中North,South,East,West的值并不等于0,1,2,3,而是他们本身就是自己的值,且该值的类型就是CompassPoint
var directionToHead = CompassPoint.West
// directionToHead是一个CompassPoint类型,可以被赋值为该类型的其他值// 当设置directionToHead的值时,他的类型是已知的,因此可以省略East的类型
directionToHead = .East
directionToHead = .South
switch directionToHead {
case .North:
println("Lots of planets have a north")
case .South:
println("Watch out for penguins")
case .East:
println("Where the sun rises")
case .West:
println("Where the skies are blue")
}
enum Barcode {
case UPCA(Int, Int, Int)
case QRCode(String)
}
// 定义一个变量。该变量即可被赋值为3个整数,又可被赋值为一个字符串,但都是Barcode类型的枚举值var productBarcode = Barcode.UPCA(8, 85909_51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
// 使用switch时,case内可区分条形码种类,可使用变量或常量获得结合值switch productBarcode {
case .UPCA(let numberSystem, let identifier, let check):
println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let productCode):
println("QR code with value of \(productCode).")
}
// 打印 "QR code with value of ABCDEFGHIJKLMNOP."
*在case内部,如果其类型都为let或var,则该关键字可提前到case和枚举类型中间,如:
caselet .UPCA(numberSystem, identifier, check):