swift-使用 Switch 语句匹配枚举值 官网
在 Swift 里,可借助 Switch 语句匹配枚举值。枚举是自定义类型,含一组相关值。Switch 语句能按枚举成员不同执行不同代码。 enum Direction { case north case south case east case west}let currentDirection = Direction.northswitch currentDirection { case .north: print(向北) case .south: print(向南) case .east: print(向东) case .west: print(向西)} 上述代码先定义 Direction 枚举,有 north、south、east、west 成员。再设 currentDirection 为 north,用 Switch 语句依其值输出对应方向。 用 Switch 匹配枚举时,要保证涵盖枚举所有成员,不然编译会报错。若不想处理所有成员,可用 default 分支。