枚举定义了一个通用类型的一组相关的值,使咱们能够在本身的代码中以一个安全的方式来使用这些值。安全
枚举的结构:bash
enum SomeEnumeration {
// enumeration definition goes here
}
复制代码
枚举的使用:网站
// 定义枚举
enum Direction {
case east
case south
case west
case north
}
// 调用枚举
var direct = Direction.east
print("如今的方向是:\(direct)")
out:
如今的方向是:east
复制代码
定义枚举时,里面的case看上去就是为switch准备的,天生一对.ui
// 调用枚举
var direct = Direction.east
switch direct {
case Direction.east:
do{
print("如今的方向是:东")
}
case Direction.south:
do{
print("如今的方向是:南")
}
case Direction.west:
do{
print("如今的方向是:西")
}
case Direction.north:
do{
print("如今的方向是:北")
}
}
out:
如今的方向是:东
复制代码
咱们能够定义Swift的枚举存储任何类型的相关值,若是须要,每一个成员的数据类型能够是各不相同的。枚举的这种特性与其余语言中的可辨识联合,标签联合,或变体类似。例如,假设一个库存跟踪系统须要利用两种不一样类型的条形码来跟踪商品。spa
var goods = Barcode.UPCA(8, 855, 11, 3)
goods = Barcode.QRCode("TEST")
switch goods {
case let .UPCA(first, second, third, forth):
do{
print("first is:\(first), second is \(second), third is \(third), forth is \(forth)")
}
case let .QRCode(qr):
do{
print("qr is \(qr)")
}
}
out:
qr is TEST
复制代码
做为性管制的替代物,枚举成员能够被默认值(原始值)预填充,这些原始值有相同的类型,如:.net
enum Animate: Int {
case pig = 1
case dog
case bird
case frog
}
print("dog 的初始值:\(Animate.dog.rawValue),hashValue:\(Animate.dog.hashValue)")
out:
dog 的初始值:2,hashValue:1
复制代码
我的网站code
微博:顺扬skyget
简书:顺扬sky博客
掘金:顺扬skystring