Image Description

枚举是为一组相关的值定义的一个公共类型,用关键词 enum 定义。

定义一个枚举

enum Movement {
    case north
    case south
    case east
    case west
}

用Switch 语句来匹配枚举值

let aMovement = Movement.south

switch aMovement {
case .south:
    print("South")
case .north:
    print("North")
default:()
    print("West or east")
}

比较

if aMovement == .south {
    print("South")
}

枚举支持的类型

Swift中的枚举支持整型(interger),浮点数(float),字符串(string),布尔(bool)

enum Movement:Int {
    case north = 0
    case south = 1
    case east = 2
    case west = 3
}

在一个枚举中定义的值(比如: north, south, east和 west)就是枚举的成员值,case关键字则明确了要定义成员值。

enum Area: String {
    case DG = "dongguan"
    case GZ = "guangzhou"
    case SZ = "shenzhen"
}

枚举还可以嵌套

enum Area {
    enum DongGuan {
        case NanCheng
        case DongCheng
    }
    
    enum GuangZhou {
        case TianHe
        case CheBei
    }
}
print(Area.DongGuan.DongCheng)

枚举里面声明枚举