枚举语法
使用关键字 enum 定义一个枚举
enum SomeEnumeration {
// enumeration definition goes here
}
例如,指南针有四个方向:
enum CompassPoint {
case north
case south
case east
case west
}
这里跟 c 和 objective-c 不一样的是,Swift 的枚举成员在创建的时候没有给予默认的整型值。所以上面代码中的东南西北并不是0到3,相反,不同的枚举类型本身就是完全成熟的值,具有明确定义的CompassPoint类型。
也可以声明在同一行中:
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
枚举赋值:
var directionToHead = CompassPoint.west
一旦 directionToHead 明确为 CompassPoint 类型的变量,后面就可以使用点语法赋值:
directionToHead = .east
Switch 表达式的枚举值匹配
switch 表达式如下:
directionToHead = .south
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}
// Prints "Watch out for penguins"
当然这里也可以加上 default 以满足所有的情况:
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
// Prints "Mostly harmless"
关联值
在 Swift 中,使用枚举来定义一个产品条形码:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
可以这样理解上面这段代码:定义一个叫 Barcode 的枚举类型,带有值类型(Int,Int,Int,Int)的 upc和值类型(String)
现在可以这样创建其中一种类型的条形码:
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
同一产品的另外一个类型的条形码可以这样赋值:
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
可以用 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).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."
上面的写法也可以改为:
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC : (numberSystem), (manufacturer), (product), (check).")
case let .qrCode(productCode):
print("QR code: (productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."








